/* Core.js */
function TianvUI() { return this; }
var UI = new TianvUI();

TianvUI.prototype.BasePath = '/admin/ui/';
TianvUI.prototype.BlankImg = UI.BasePath + 'images/blank.gif';

TianvUI.prototype.AutoResizeAble = function ($el, fn) {
    var autoResizeTime = 15;
    function autoResize() {
        var $parent = $el.parent();
        if ($parent.length <= 0) {
            setTimeout(autoResize, autoResizeTime);
            return;
        }
        $parent.resize(function () {
            var pow = $el.data('pw');
            var poh = $el.data('ph');
            var pw = $parent.width();
            var ph = $parent.height();
            if (pow != pw || poh != ph) {
                $el.data('pw', pw);
                $el.data('ph', ph);
                fn(pw, ph);
            }
        });
        fn($parent.width(), $parent.height());
    }
    $el.ready(autoResize);
};

var elementClearFns = new Array();
TianvUI.prototype.Clear = function ($el) {
    for (var i = 0; i < elementClearFns.length; i++) {
        var fn = elementClearFns[i];
        fn($el);
    }
}

elementClearFns.push(function ($el) {
    $el.find('.flash').hide();
});
elementClearFns.push(function ($el) {
});

var formInit = new Array();
var formDestroy = new Array();

var windowResizeFns = new Array();
var windowResizeTimer = null;
$(window).resize(function () {
    if (windowResizeTimer) clearTimeout(windowResizeTimer);
    windowResizeTimer = setTimeout(function () {
        for (var i = 0; i < windowResizeFns.length; i++) {
            var fn = windowResizeFns[i];
            fn();
        }
    }, 100);
});

var createUIFns = new Array();
TianvUI.prototype.CreateUI = function ($el, data) {
    if (data && typeof (data.type) != 'undefined') {
        for (var i = 0; i < createUIFns.length; i++) {
            var fn = createUIFns[i];
            fn($el, data);
        }
    }
};

var hrefClickFns = new Array();
$(document).delegate("a", "click", function () {
    var $this = $(this);
    for (var i = 0; i < hrefClickFns.length; i++) {
        var fn = hrefClickFns[i];
        var processed = fn($this);
        if (processed) {
            return false;
        }
    }
    return true;
});

/* Tianv.UI.Frame.js */
var elements = {
    body: $('body'),
    logo: $('#logo'),
    frame: {
        top: $('#frame_top'),
        left: $('#frame_left'),
        main: $('#frame_main'),
        foot: $('#frame_foot')
    },
    slider: {
        horizontals: $('div.slider_horizontal'),
        verticals: $('div.slider_vertical'),
        top: $('#slider_top'),
        left: $('#slider_left'),
        center: $('#slider_center'),
        right: $('#slider_right'),
        bottom: $('#slider_bottom')
    }
};



(function ($) {

    windowResizeFns.push(function () {
        elements.frame.left.trigger('resize');
        elements.frame.main.trigger('resize');
    });

    if (elements.slider.center.length >= 1) {
        elements.slider.center.draggable({
            axis: 'x',
            helper: 'clone',
            opacity: 0.35,
            stop: function (event, ui) {
                var me = $(this);
                var slider_center_old = ui.originalPosition.left;// me.data('old_left');
                var slider_center_new = ui.position.left;// event.clientX; // me.position().left; //.find('~ #slider_center')
                if (slider_center_new == slider_center_old || Math.abs(slider_center_new - slider_center_old)<=5)
                    return;

                if (slider_center_new <= 150) slider_center_new = 150;
                if (slider_center_new >= 400) slider_center_new = 400;

                me.css('left', slider_center_new);
                elements.frame.left.width(slider_center_new - elements.slider.left.width() - 2);
                elements.frame.main.css('left', slider_center_new + elements.slider.center.width());
                if ($.browser.msie && $.browser.version < 7) {
                    var th_width = elements.frame.left.outerWidth() + elements.slider.left.width() + elements.slider.center.width() + elements.slider.right.width();
                    elements.frame.main.width(elements.body.width() - th_width - 2);
                }

                elements.frame.left.trigger('resize');
                elements.frame.main.trigger('resize');
            }
        });
    };

})(jQuery);



/* Tianv.UI.Botton.js */
(function ($) {

    function TianvBotton(type, text, fn) {
        /// <summary>生成按钮</summary>
        /// <param name="type">按钮类型</param>
        /// <param name="text">按钮文本</param>
        /// <param name="fn">按钮函数</param>

        this.type = type;
        this.text = text;
        this.fn = fn;
        this.$el = null;
        this.$form = null;
        return this;
    }

    TianvBotton.prototype =
    {
        Show: function () {
            var $this = this;

            var text;
            if ($this.text) {
                text = Utils.htmlEncode($this.text);
            }
            else if ($this.type && $this.type == 'submit') {
                text = lan.Form.Button.Submit;
            }
            else if ($this.type && $this.type == 'reset') {
                text = lan.Form.Button.Reset;
            }


            var button_text = '<div class="button"><span>' + text + '</span></div>';
            var $el = $(button_text);

            $el.hover(function () {
                if (!$(this).attr('disabled')) $(this).addClass('hover');
            }, function () {
                if (!$(this).attr('disabled')) $(this).removeClass('hover');
            }).mousedown(function () {
                if (!$(this).attr('disabled')) $(this).addClass('down');
            }).mouseup(function () {
                if (!$(this).attr('disabled')) $(this).removeClass('down');
            }).mouseout(function () {
                if (!$(this).attr('disabled')) $(this).removeClass('down');
            }).bind('selectstart', function () {
                return false;
            }).click(function () {
                if ($this.fn == undefined) {
                    if (!$this.$form) return;
                    if ($this.$form.length <= 0) return;
                    if ($this.type == 'submit') {
                        $this.$form[0].submit();
                    }
                    else if ($this.type == 'reset') {
                        $this.$form[0].reset();
                    }
                    return;
                }
                $this.fn($this.$form);
            }).ready(function () {
                var $form = $el.closest('form');
                if ($form && $form.length) $this.$form = $form;
            });

            $this.$el = $el;

            return $el;
        },
        Disable: function () {
            var $this = this
            var $el = $this.$el;
            $el.attr('disabled', 'disabled');
        }
    };

    TianvUI.prototype.Button = {
        Create: function (type, text, fn) {
            /// <summary>生成按钮</summary>
            /// <param name="type">按钮类型</param>
            /// <param name="text">按钮文本</param>
            /// <param name="fn">按钮函数</param>

            var ui = new TianvBotton(type, text, fn);
            $el = ui.Show();
            $el.data('ui', ui);

            return $el;
        },
        Disable: function ($el) {
            var button = $el.data('ui');
            if (!button) return;

            button.Disable();
        }
    }

    formInit.push(function ($form) {
        $form.find('>.btns input').each(function () {
            var button = $(this);
            var button_type = button.attr('type');
            var button_text = button.attr('value');
            var btn = UI.Button.Create(button_type, button_text, null);
            btn.insertAfter(button);
            button.remove();
        });
    });

})(jQuery);

/* Tianv.UI.Accordion.js */
(function ($) {

    function TianvAccordion(data, height) {
        /// <summary>生成滑动面板</summary>
        /// <param name="data">面板数据</param>
        /// <param name="height">高度</param>

        this.data = data;
        this.height = height;
        this.$el = null;
        return this;
    }

    var loading = [
'    <div class="loading">',
'        <img src="' + UI.BasePath + 'view/accordion/loading.gif" alt="" />',
'    </div>'
].join('');

    TianvAccordion.prototype =
    {
        getTitle: function (item) {
            /// <summary>面板头部</summary>
            /// <param name="item">节点数据</param>

            var $this = this;

            var title_text = [
'<a href="javascript:void(0)" class="accordion_title">',
'    ' + Utils.getIcon(item.icon),
'    <span class="title">' + item.text + '</span>',
'    <span class="refresh"></span>',
'</a>'
].join('');
            var $title = $(title_text);
            if (item.href) {
                $title.data('href', item.href);
            }
            $title.click(function () {
                if ($title.hasClass('active'))
                    return;
                $this.toggle($(this));
            });
            $title.find('.refresh').click(function () {
                $this.reload($title);
            });
            return $title;
        },
        getContent: function (item) {
            /// <summary>面板内容</summary>
            /// <param name="item">节点数据</param>

            var content_text = [
'<div class="accordion_content">',
loading,
'</div>'
].join('');
            var $content = $(content_text);
            return $content;
        },
        reload: function ($title) {
            var $content = $title.next();
            $content.html(loading);

            var href = $title.data('href');
            var nhref = href;
            if (href && href.indexOf('/') != 0) {
                nhref = Utils.getAdminCodeFile(href);
            }

            if (href ) {
                $.ajax({
                    url: nhref,
                    dataType: 'json',
                    success: function (data) {
                        UI.CreateUI($content, data);

                        $content.find('a').draggable({
                            distance: 20,
                            appendTo: "body",
                            helper: "clone"
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        var errorString = Utils.getText('lan.Ajax.Error.E' + xhr.status);
                        $content.html('<div class="error">' + errorString + '</div>');
                    }
                });
            }
            else {
                var item = $title.data('settings');
                if (item.content) {
                    $content.html(item.content);
                }
            }
        },
        toggle: function ($title) {
            /// <summary>收缩/展开</summary>
            /// <param name="$title">面板头部</param>

            var $container = $title.parent();
            var $content = $title.next();

            $container.find('.accordion_title').removeClass('active');
            $container.find('.accordion_content').hide();

            $title.addClass('active');
            $content.show();
            this.reload($title);
        },
        Show: function () {
            var $this = this;

            var $el = $('<div class="accordion"></div>');
            for (var i = 0; i < this.data.items.length; i++) {
                var item = this.data.items[i];
                if (item.hide)
                    continue;
                $title = this.getTitle(item);
                $title.data('settings', item);
                $content = this.getContent(item);
                $el.append($title);
                $el.append($content);
                if (i == 0) {
                    $title.addClass('active');
                    $this.reload($title);
                }
                else {
                    $content.hide();
                }
            }

            $this.$el = $el;

            if ($this.height <= 0) {
                $el.css('visibility', 'hidden');
                UI.AutoResizeAble($el, function (w, h) {
                    $this.height = h;
                    $this.Resize();
                    $el.css('visibility', 'visible');
                });
            }
            else {
                $this.Resize();
            }

            return $el;
        },
        Resize: function () {

            var $this = this;
            var height = $this.height;
            if (height <= 0)
                return;

            var content_height = height;
            for (var i = 0; i < this.data.items.length; i++) {
                var item = this.data.items[i];
                if (item.hide)
                    continue;
                content_height -= 25;
            }

            if (content_height >= 1) {
                $this.$el.find('.accordion_content').height(content_height);
            }
        }
    };

    TianvUI.prototype.Accordion = function (data, height) {
        /// <summary>生成滑动面板</summary>
        /// <param name="data">面板数据</param>
        /// <param name="height">面板高度(随容器自动增长请留空)</param>

        var h = 0;
        if (Utils.isNumber(height) && height >= 1) h = height;

        var ui = new TianvAccordion(data, h);
        $el = ui.Show();
        $el.data('ui', ui);

        return $el;
    };

})(jQuery);

/* Tianv.UI.Tree.js */
(function ($) {

    function TianvTree(data) {
        /// <summary>生成树形</summary>
        /// <param name="data">树形数据</param>

        this.data = data;
        return this;
    }

    function TianvTreeNode(parent, nodes, node, index, level) {
        /// <summary>树形节点</summary>
        /// <param name="parent" type="TianvTreeNode">上级</param>
        /// <param name="nodes">平级</param>
        /// <param name="node">当前元素</param>
        /// <param name="index">位置</param>
        /// <param name="level">深度</param>

        this.parent = parent;
        this.nodes = nodes;
        this.node = node;
        this.index = index;
        this.level = level;

        this.hasPre = (index >= 1);
        this.hasNext = false; // (index < nodes.length - 1);
        if (index < nodes.length - 1) {
            for (var i = index + 1; i < nodes.length; i++) {
                if (!nodes[i].hide) {
                    this.hasNext = true;
                    break;
                }
            }
        }
        this.hasChild = false; // ((node.nodes && node.nodes.length >= 1) ? true : false);
        if (node.nodes && node.nodes.length >= 1) {
            for (var i = 0; i < node.nodes.length; i++) {
                if (!node.nodes[i].hide) {
                    this.hasChild = true;
                    break;
                }
            }
        }
        return this;
    }

    TianvTree.prototype =
    {
        getLine: function (name) {
            return '<img src="' + UI.BlankImg + '" alt="" class="treeline treeline_' + name + '" />';
        },
        getLine1: function (tn) {
            /// <summary>第一条线</summary>
            /// <param name="tn" type="treeNode">当前节点</param>

            if (tn.level == 1)
                return '';

            if (tn.parent.hasNext)
                return this.getLine('I');
            else
                return this.getLine('noexpand');
        },
        getLine2: function (tn) {
            /// <summary>第二条线</summary>
            /// <param name="tn" type="treeNode">当前节点</param>

            if (!tn.hasChild) {
                var nHasPre = tn.level >= 2 ? true : tn.hasPre;
                if (nHasPre && tn.hasNext) {
                    return this.getLine('T');
                }
                else if (nHasPre) {
                    return this.getLine('L');
                }
                else if (tn.hasNext) {
                    return this.getLine('R');
                }
                else {
                    return this.getLine('Dash');
                }
            }
            else {
                var bIcon = tn.node.opened ? 'minus' : 'plus';
                if (tn.hasPre && tn.hasNext) {
                    return this.getLine('T' + bIcon);
                }
                else if (tn.hasPre) {
                    return this.getLine('L' + bIcon);
                }
                else if (tn.hasNext) {
                    return this.getLine('R' + bIcon);
                }
                else {
                    return this.getLine('D' + bIcon);
                }
            }
        },
        setSwicthAble: function (tn, line2) {
            /// <summary>按钮(收缩/展开)</summary>
            /// <param name="tn" type="treeNode">当前节点</param>
            /// <param name="line2">第二条线</param>

            if (!tn.hasChild) {
                return line2;
            }
            var sw = $(line2);
            sw.addClass('treeline_sw');

            var $this = this;
            sw.click(function () {
                var me = $(this);
                var $li = me.parent().parent();
                $this.toggle($li);
            });

            return sw;
        },
        toggle: function ($li) {
            /// <summary>收缩/展开</summary>
            /// <param name="$li">li节点</param>

            var sw = $li.children('div').children('img.treeline_sw');
            var me_ul = $li.children('ul');

            var me_c = sw.attr('class');
            if (me_c.indexOf('plus') >= 0) {
                me_ul.slideDown(100, function () {
                    sw.attr('class', me_c.replace('plus', 'minus'));
                });
            }
            else {
                me_ul.slideUp(100, function () {
                    sw.attr('class', me_c.replace('minus', 'plus'));
                });
            }
        },
        makeNodes: function ($parents, parent, nodes, level, pLine) {
            /// <summary>生成树形文档(递归)</summary>
            /// <param name="$parents">文档</param>
            /// <param name="parent" type="treeNode">上级</param>
            /// <param name="nodes">平级</param>
            /// <param name="node">当前元素</param>
            /// <param name="index">位置</param>
            /// <param name="level">深度</param>

            if (!nodes) return;
            if (!$parents) $parents = $('<ul class="tree level_1"></ul>');
            if (level) level++; else level = 1;
            for (var i = 0; i < nodes.length; i++) {
                var node = nodes[i];
                if (node.hide) continue;

                var li = $('<li></li>');
                var div = $('<div></div>');
                div.appendTo(li);
                if (pLine) div.append(pLine);

                var tn = new TianvTreeNode(parent, nodes, node, i, level);

                var line1 = this.getLine1(tn);
                if (line1 && line1.length >= 1) div.append(line1);

                var line2 = this.getLine2(tn);
                var sw = this.setSwicthAble(tn, line2);
                div.append(sw);

                var li_a = Utils.getSmallButton(node, false, true);

                div.append(Utils.getIcon(node.icon));
                div.append(li_a);
                li.appendTo($parents);

                if (tn.hasChild) {
                    var nEl = $('<ul class="level_' + (level + 1) + '"></ul>');
                    this.makeNodes(nEl, tn, node.nodes, level, (pLine ? pLine : '') + line1);
                    if (!node.opened) nEl.hide();
                    nEl.appendTo(li);
                }

                if (tn.hasChild && node.href.indexOf('javascript:') == 0) {
                    var $this = this;
                    li_a.click(function () {
                        $this.toggle($(this).parent().parent());
                    });
                }
            }
            return $parents;
        },
        Show: function () {
            var $this = this;
            var nodes = $this.makeNodes(null, null, this.data.nodes);
            return nodes;
        }
    };

    TianvUI.prototype.Tree = function (data) {
        /// <summary>生成树形文档</summary>
        /// <param name="data">树形结构</param>

        var ui = new TianvTree(data);
        var $el = ui.Show();
        $el.data('ui', ui);
        return $el;
    };

    createUIFns.push(function ($el, data) {
        if (data.type != 'tree')
            return;
        var $item = UI.Tree(data);
        $el.html($item);
        //$item.html();
    });

})(jQuery);

/* Tianv.UI.Tab.js */
(function ($) {

    var _tempt_page_tab = [
'<div class="tabs">',
'   <div class="tabs_title">',
'      <ul>',
'          <li><a href="Html/Home/default.html"><span>' + lan.Default.Desktop + '</span></a></li>',
'          {{each(index, item) items}}',
'          {{if hide}}{{else}}',
'          <li{{if index==current}} class="curr"{{/if}}><a href="${href}"><span>${title}</span></a></li>',
'          {{/if}}',
'          {{/each}}',
'      </ul>',
'   </div>',
'   <div class="tabs_content">',
'   </div>',
'</div>',
].join('');
    $.template("pageTab", _tempt_page_tab);

    function TianvTab(data, width, height) {
        /// <summary>生成Tab</summary>
        /// <param name="data">数据</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>

        this.width = width;
        this.height = height;
        this.data = data;
        this.$el = null;
        return this;
    }

    TianvTab.prototype =
    {
        Resize: function () {
            var $this = this;
            var $el = $this.$el;
            $el.width($this.width);
            $el.height($this.height);
            var $content = $el.find('>.tabs_content');
            $content.height($this.height - 27);
            setTimeout(function () { $content.trigger('resize'); }, 60);
        },
        Show: function () {
            var $this = this;
            var $el = $.tmpl("pageTab", $this.data);
            this.$el = $el;

            if ($this.height <= 0 || $this.width <= 0) {
                $el.css('visibility', 'hidden');
                UI.AutoResizeAble($el, function (w, h) {
                    $this.width = w;
                    $this.height = h;
                    $this.Resize();
                    $el.css('visibility', 'visible');
                });
            }
            else {
                $this.Resize();
            }

            return $el;
        }
    };

    TianvUI.prototype.Tab = function (data, width, height) {
        /// <summary>生成Tab文档</summary>
        /// <param name="data">Tab结构</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>

        var w = 0;
        if (Utils.isNumber(width) && width >= 1) w = width;

        var h = 0;
        if (Utils.isNumber(height) && height >= 1) h = height;

        var ui = new TianvTab(data, w, h);
        var $el = ui.Show();
        $el.data('ui', ui);
        return $el;
    };

})(jQuery);

/* Tianv.UI.Hbox.js */
(function ($) {

    var _tempt_home_box = [
'<div class="home_box">',
'   <div class="home_box_wap clearfix">',
'       <div class="home_box_title inlinemiddle">',
'           <img src="' + UI.BlankImg + '" alt="" class="picon picon_${icon}" />',
'           <span>${title}</span>',
'       </div>',
'       <div class="home_box_detail">{{if htmlData}}{{html htmlData}}{{/if}}',
'       </div>',
'   </div>',
'</div>'].join('');
    $.template("home_box", _tempt_home_box);

    // home_box_{{if size}}${size}{{else}}full{{/if}}"{{if width}} style="width:${width}px;"{{/if}}
    //{{if aClass}} ${aClass}{{/if}}

    function TianvHBox(data) {
        /// <summary>生成文档</summary>
        /// <param name="data">文档数据</param>

        this.data = data;
        this.$el = null;
        return this;
    }

    TianvHBox.prototype =
    {
        updateWidth: function () {
            var $this = this;
            var $el = $this.$el;
            var $parent = $el.parent();
            var w = $parent.width();
            var nw = ((w - 9 * 9) * $this.data.size / 8) + ($this.data.size - 1) * 9;
            $el.width(Math.floor(nw));
        },
        Show: function () {
            var $this = this;
            var $el = $.tmpl("home_box", $this.data);
            if ($this.data.newLine) {
                $el.css('clear', 'both');
            }
            $el.css('visibility', 'hidden');
            if ($this.data.size) {
                UI.AutoResizeAble($el, function (w, h) {
                    $this.updateWidth();
                    $el.css('visibility', 'visible');
                });
            }
            $this.$el = $el;
            return $el;
        }
    };

    TianvUI.prototype.HBox = function (data) {
        /// <summary>生成文档</summary>
        /// <param name="data">文档结构</param>

        var ui = new TianvHBox(data);
        var $el = ui.Show();
        $el.data('ui', ui);
        return $el;
    };

})(jQuery);

/* Tianv.UI.BIcon.js */
(function ($) {

    //var _tempt_icon = '<a href="${href}"{{if confirm}} confirm="confirm" confirm_title="${confirm.title}" confirm_text="${confirm.text}"{{/if}}{{if target}} target="${target}"{{/if}}{{if dbox}} target="dbox" boxicon="${dbox.icon}" boxwidth="${dbox.width}" boxheight="${dbox.height}"{{/if}}><img src="' + (Config_Configs.Admin.Remote.Icons ? (Conf.RemoteHost + '/') : Conf.Paths.Remote) + 'icon/${icon}.png" alt="" /><span title="${alt}">{{html title}}</span></a>';
    var _tempt_icon = '<a href="${item.href}"{{if item.confirm}} confirm="confirm" confirm_title="${item.confirm.title}" confirm_text="${item.confirm.text}"{{/if}}{{if item.target}} target="${item.target}"{{/if}}{{if item.dbox}} target="dbox" boxicon="${item.dbox.icon?item.dbox.icon:item.icon}" boxwidth="${item.dbox.width}" boxheight="${item.dbox.height}"{{/if}}><img src="' + (Config_Configs.Admin.Remote.Icons ? (Conf.RemoteHost + '/') : Conf.Paths.Remote) + 'icon/${item.icon}.png" alt="" /><span title="${item.alt}">{{html item.title}}</span></a>';
    $.template("bigicon", _tempt_icon);

    var _tempt_bicon = [
'<div class="bicon">',
'   <ul>',
'   {{each(index, item) items}}',
'       {{if newline}}',
'   </ul>',
'   <ul style="clear: left;">',
'       {{else item.hide}}',
'       {{else skip}}',
'       <li>',
'       </li>',
'       {{else}}',
'       <li>',
'           ' + _tempt_icon,
'       </li>',
'       {{/if}}',
'   {{/each}}',
'   </ul>',
'</div>'].join('');
    $.template("bicon", _tempt_bicon);

    function TianvBIcon(data) {
        /// <summary>生成树形</summary>
        /// <param name="data">树形数据</param>

        this.data = data;
        this.$el = null;
        return this;
    }

    TianvBIcon.prototype =
    {
        Show: function () {
            var $this = this;
            var $el = $.tmpl("bicon", $this.data);
            $this.$el = $el;
            return $el;
        }
    };

    TianvUI.prototype.BIcon = function (data) {
        /// <summary>生成树形文档</summary>
        /// <param name="data">树形结构</param>

        var ui = new TianvBIcon(data);
        var $el = ui.Show();
        $el.data('ui', ui);
        return $el;
    };

    TianvUI.prototype.getIcon = function (data) {
        return $.tmpl("bigicon", { item: data });
    };

})(jQuery);

/* Tianv.UI.Box.js */
(function ($) {

    var _tempt_box = [
'<div class="box">',
'   <table cellpadding="0" cellspacing="0" border="0" class="box_shadow box_bg">',
'       <tr><td class="top top_left">&nbsp;</td><td class="top top_center">&nbsp;</td><td class="top top_right">&nbsp;</td></tr>',
'       <tr><td class="mid mid_left">&nbsp;</td><td class="mid mid_center">&nbsp;</td><td class="mid mid_right">&nbsp;</td></tr>',
'       <tr><td class="bot bot_left">&nbsp;</td><td class="bot bot_center">&nbsp;</td><td class="bot bot_right">&nbsp;</td></tr>',
'   </table>',
'   <table cellpadding="0" cellspacing="0" border="0" class="box_rounded box_bg">',
'       <tr><td class="top top_left">&nbsp;</td><td class="top top_center">&nbsp;</td><td class="top top_right">&nbsp;</td></tr>',
'       <tr><td class="mid mid_left">&nbsp;</td><td class="mid mid_center">&nbsp;</td><td class="mid mid_right">&nbsp;</td></tr>',
'       <tr><td class="bot bot_left">&nbsp;</td><td class="bot bot_center">&nbsp;</td><td class="bot bot_right">&nbsp;</td></tr>',
'   </table>',
'   <div class="box_title">{{if close}}<img src="' + UI.BlankImg + '" alt="" title="lan.Box.Close" class="btn btn_close" />{{/if}}{{if refresh}}<img src="' + UI.BlankImg + '" alt="" title="lan.Box.Refresh" class="btn btn_refresh" />{{/if}}<img src="' + UI.BlankImg + '" alt="" class="picon picon_${icon}" /><span class="title">{{html title}}</span></div>',
'   <div class="box_container">',
'       <div class="msg">',
'            <div class="border_out"><div class="border_in">&nbsp;',
'            </div></div>',
'            <div class="btns"></div>',
'        </div>',
'        <div class="main">',
'            <div class="border_out"><div class="border_in">{{if htmlData}}{{html htmlData}}{{/if}}',
'            </div></div>',
'            <div class="btns"></div>',
'        </div>',
'   </div>',
'</div>'
].join('');
    $.template("box", _tempt_box);

    //默认选项 
    var defaultSettings = {
        width: 320,
        height: 120,
        icon: 'application',
        close: true,
        refresh: true
    };

    function TianvBox(data) {
        /// <summary>生成弹出框</summary>
        /// <param name="data">设置数据, 参考内容：{width:0,height:0,icon:0,title:'',close:true,refresh:false}</param>

        this.opts = $.extend({}, defaultSettings, data || {});

        this.width = data.width >= 1 ? data.width : defaultSettings.width;
        this.height = data.height >= 1 ? data.height : defaultSettings.height;
        this.icon = this.opts.icon; // data.icon;
        this.close = this.opts.close;
        this.refresh = this.opts.refresh;

        this.data = this.opts;
        this.guid = Utils.getGuid();
        this.title = data.title;
        this.url = data.url;
        this.$el = null;
        return this;
    }

    TianvBox.prototype =
    {
        autoElementResize: function () {
            var $this = this;
            var $el = $this.$el;

            $el.children('.box_container').resize(function () {
                var container = $(this);
                var width = container.width();
                var height = container.height();

                $el.css({ width: width + 12, height: height + 34 });
                $el.children('.box_shadow').css({ width: width + 12, height: height + 34 });
                $el.find('.box_shadow td.mid').css({ height: height + 22 });
                $el.children('.box_rounded').css({ width: width + 8, height: height + 30 });
                $el.find('.box_rounded td.mid').css({ height: height });
                //$el.children('.box_container').css({ width: width, height: height });
                $el.find('.border_in').height(height - 16 - 34);
            });
        },
        draggAble: function () {
            var $this = this;
            var $el = $this.$el;

            //可拖动
            $el.draggable({ handle: '.box_title', scroll: false, stack: ".box",
                cancel: '.btn', zIndex: 9,
                start: function (event, ui) { var me = $(this); me.addClass('box_move'); me.css("opacity", 0.35); },
                stop: function (event, ui) { var me = $(this); me.removeClass('box_move'); me.css("opacity", 1); }
            });
            $el.find('div.title').bind('selectstart', function () {
                return false;
            });
            $el.css({ 'position': 'absolute' });
        },
        closeAble: function () {
            var $this = this;
            var $el = $this.$el;
            if ($this.close) {
                $el.find('img.btn_close').mousedown(function () {
                    $(this).addClass('btn_close_over').removeClass('btn_close');
                })
                .mouseup(function () {
                    $(this).addClass('btn_close').removeClass('btn_close_over');
                })
                .click(function () {
                    $this.Close();
                });
            }
        },
        refreshAble: function () {
            var $this = this;
            var $el = $this.$el;
            if ($this.refresh) {
                $el.find('img.btn_refresh').mousedown(function () {
                    $(this).addClass('btn_refresh_over').removeClass('btn_refresh');
                })
                .mouseup(function () {
                    $(this).addClass('btn_refresh').removeClass('btn_refresh_over');
                })
                .click(function () {
                    $this.Refresh();
                });
            }
        },
        autoPlace: function () {
            var $this = this;
            var $el = $this.$el;

            var nleft = ($(document).width()) / 2 - (parseInt($this.width) / 2);
            if (nleft <= 0) nleft = 200;
            var ntop = ($(document).height()) / 2 - (parseInt($this.height) / 2);
            if (ntop <= 0) ntop = 60;
            $el.css({ top: ntop, left: nleft });
        },
        autoIndex: function () {
            var $this = this;
            var $el = $this.$el;

            var nIndex = 200;
            $('.box').each(function () {
                var $me = $(this);
                var meIndex = parseInt($me.css("z-index"));
                if(meIndex>= nIndex) {
                    nIndex = meIndex + 1;
                }
            });
            $el.css("z-index", nIndex);
        },
        setSize: function (width, height) {
            var $this = this;
            var $el = $this.$el;
            $this.width = width;
            $this.height = height;
            var container = $el.children('.box_container');
            container.css({ width: width, height: height });
            container.trigger('resize');
        },
        clean: function ($el) {
            var aj = $el.data('ajax');
            if (aj) aj.abort();

            UI.Clear($el);
        },
        showLoading: function () {
            var $this = this;
            $this.Msg.showLoading($this);
        },
        Close: function () {
            var $this = this;
            var $el = $this.$el;

            $this.clean($el);

            if ($.browser.msie) {
                $el.hide().remove();
            }
            else {
                $el.addClass('box_move');
                $el.fadeOut(100, function () {
                    $el.remove();
                });
            }
        },
        Refresh: function () {
            var $this = this;
            var $el = $this.$el;

            $this.clean($el);

            var oaj = $el.data('ajax');
            if (oaj) oaj.abort();

            $this.showLoading();

            var aj = $.ajax({
                url: $this.url,
                cache: false,
                success: function (data) {
                    var uname = Utils.getDirName($this.url);
                    var sname = Utils.getSecondDirName($this.url);
                    var lname = Utils.getLastDirName($this.url);
                    if (uname != null && uname.length >= 1) {
                        $this.showHtml(data.replace('{uname}', uname).replace('{sname}', sname).replace('{lname}', lname).replace('{guid}', $this.guid));
                    }
                    else {
                        $this.showHtml(data.replace('{guid}', $this.guid));
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $this.showError(xhr, ajaxOptions, thrownError);
                }
            });
            $el.data('ajax', aj);
        },
        showResult: function (data, reutrnAble) {
            var $this = this;

            //自动刷新内容
            if (data.refresh) {
                Views.Page.ReflashData();
            }
            //自动刷新菜单
            if (data.refreshmenu) {
                Views.Page.ReflashMenu();
                //refreshTree();
            }
            //自动刷新菜单
            if (data.refreshBox) {
                //alert(data.refreshBox);
                var bguid = data.refreshBox;
                var $box = $('#box_' + bguid);
                var box = $box.data('ui');
                //alert([bguid, $box, box]);
                box.Refresh();
            }
            var str = data.str;
            if (str.indexOf('lan.') == 0) {
                if (data.args != null) {
                    str = Utils.getText(str).replace('{0}', data.args);
                }
                else {
                    str = Utils.getText(str);
                }
            }
            else {
                str = data.str;
            }

            if (data.success) {
                $this.Msg.showTip($this, str, function () {
                    $this.Close();
                });
                setTimeout(function () {
                    $this.Close();
                }, 500);
            }
            else {
                var $el = $this.$el;
                if (reutrnAble) {
                    $this.Msg.showError($this, str, function () {
                        var bMain = $el.find('div.box_container >.main');
                        var bMsg = $el.find('div.box_container >.msg');
                        bMain.show();
                        bMsg.hide();
                    });
                }
                else {
                    $this.Msg.showError($this, str, function () {
                        $this.Close();
                    });
                }
            }
        },
        processUrl: function (ids) {
            var $this = this;
            var $el = $this.$el;

            $this.showLoading();

            var oaj = $el.data('ajax');
            if (oaj) oaj.abort();

            var aj;
            if (ids && ids.length >= 1) {
                var idStr = '';
                for (var i = 0; i < ids.length; i++) {
                    if (i >= 1) idStr = idStr + '&';
                    idStr = idStr + 'id=' + ids[i];
                }
                aj = $.ajax({
                    url: $this.url,
                    data: idStr,
                    type: 'POST',
                    cache: false,
                    success: function (data) {
                        $this.showResult(data, false);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $this.showError(xhr, ajaxOptions, thrownError);
                    }
                });
            }
            else {
                aj = $.ajax({
                    url: $this.url,
                    cache: false,
                    success: function (data) {
                        $this.showResult(data, false);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $this.showError(xhr, ajaxOptions, thrownError);
                    }
                });
            }

            $el.data('ajax', aj);
        },
        processForm: function (submitUrl) {
            var $this = this;
            var $el = $this.$el;

            $this.showLoading();

            var oaj = $el.data('ajax');
            if (oaj) oaj.abort();

            var aj = $.ajax({
                url: submitUrl,
                data: $el.find('form').serialize(),
                cache: false,
                type: 'POST',
                success: function (data) {
                    $this.showResult(data, true);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $this.showError(xhr, ajaxOptions, thrownError);
                }
            });

            $el.data('ajax', aj);

            //            boxHtml.find('.input_editor_mini,.input_editor').each(function () {
            //                var sel = $(this);
            //                $.Editor.Sync(sel);
            //            });
        },
        showHtml: function (str, btns) {
            var $this = this;
            var $el = $this.$el;
            var bMain = $el.find('div.box_container >.main');
            var bMsg = $el.find('div.box_container >.msg');
            bMsg.hide();
            bMain.find('.border_in').html(str);
            bMain.show();
        },
        showButtons: function (btns) {
            var $this = this;
            var $el = $this.$el;
            var bMain = $el.find('div.box_container >.main');
            var bMsg = $el.find('div.box_container >.msg');

            bMain.find('div.btns').empty();

            if (btns && btns.length >= 1) {
                for (var i = 0; i < btns.length; i++) {
                    var btn = btns[i];
                    bMain.find('div.btns').append(btn);
                }
            }
        },
        showError: function (xhr, ajaxOptions, thrownError) {
            console.log([xhr, ajaxOptions, thrownError]);
        },
        Msg: {
            show: function (box, icon, text, btns) {
                var $el = box.$el;

                var bMain = $el.find('div.box_container >.main');
                var bMsg = $el.find('div.box_container >.msg');
                bMain.hide();
                bMsg.show();
                var html = $('<div class="msg_detail"><img src="' + UI.BasePath + 'view/grid/msg/' + icon + '.gif" alt="" /><p>' + text + '</p></div>');
                bMsg.find('div.btns').empty();
                for (var i = 0; i < btns.length; i++) {
                    var btn = btns[i];
                    bMsg.find('div.btns').append(btn);
                }
                bMsg.find('.border_in').html(html);
            },
            showLoading: function (box) {
                //var $this = this;
                var bClose = UI.Button.Create('button', lan.Box.Cancle, function () { box.Close(); });
                this.show(box, 'loading', lan.Box.Loading, [bClose]);
                return;
            },
            showConfirm: function (box, str, fn1, fn2) {
                var bYes = UI.Button.Create('button', lan.Box.Yes, fn1);
                var bNo = UI.Button.Create('button', lan.Box.No, fn2);
                this.show(box, 'question', str, [bYes, bNo]);
            },
            showError: function (box, str, fn) {
                var bOk = UI.Button.Create('button', lan.Box.Ok, fn);
                this.show(box, 'error', str, [bOk]);
            },
            showTip: function (box, str, fn) {
                var bOk = UI.Button.Create('button', lan.Box.Ok, fn);
                this.show(box, 'info', str, [bOk]);
            },
            showWarning: function (box, str, fn) {
                var bOk = UI.Button.Create('button', lan.Box.Ok, fn);
                this.show(box, 'warning', str, [bOk]);
            }
        },
        Show: function () {
            /// <summary>面板头部</summary>

            var $this = this;

            var $el = $.tmpl("box", $this.data);
            $el.find('.box_container >div').hide();
            $el.data('box', $this);
            $el.data('guid', $this.guid);
            $el.attr('id', 'box_' + $this.guid);

            Utils.setText($el);

            $this.$el = $el;
            $this.autoElementResize();
            $this.setSize($this.width, $this.height);

            $this.closeAble();
            $this.refreshAble();

            $this.draggAble();

            $this.autoPlace();

            $this.autoIndex();

            if ($this.autoClose) {
                setTimeout(function () {
                    $this.close();
                }, data.autoClose);
            }

            return $el;
        }
    };

    TianvUI.prototype.Box = function (data) {
        /// <summary>生成树形文档</summary>
        /// <param name="data">树形结构</param>

        var ui = new TianvBox(data);
        var $el = ui.Show();
        $el.data('ui', ui);

        $('body').append($el);

        return $el;
    };

    TianvUI.prototype.MessageBox = {
        getBox: function (icon, title) {
            var data = {
                width: 0,
                height: 0,
                icon: icon,
                title: title,
                close: true,
                refresh: false
            };
            var box = new TianvBox(data);
            var $el = box.Show();
            $el.data('ui', box);
            $('body').append($el);
            return box;
        },
        ShowError: function (icon, title, text) {
            var box = this.getBox(icon, title);
            box.Msg.showError(box, text, function () { box.Close(); });
        },
        ShowTip: function (icon, title, text) {
            var box = this.getBox(icon, title);
            box.Msg.showTip(box, text, function () { box.Close(); });
        },
        ShowWarning: function (icon, title, text) {
            var box = this.getBox(icon, title);
            box.Msg.showWarning(box, text, function () { box.Close(); });
        }
    };

})(jQuery);

/* Tianv.UI.Form.js */
(function ($) {

    var _tempt_form = [
'<form method="post" action="${action}" class="actionForm" id="${guid}_form" dboxid="${guid}">',
'   <div class="actionFromContainer clearfix">',
'        {{each(index, item) items}}',
'        {{if item.hide}}',
'        {{else}}',
'        {{if item.newline}}',
'        <div class="br clearfix">&nbsp;</div>',
'        {{/if}}',
'        <table class="input_item{{if item.width}} input_item_${item.width}{{else}} input_item_240{{/if}} input_item_${item.type}{{if item.aClass}} input_item_${item.type}_${item.aClass}{{/if}}{{if item.newline}} newline{{/if}}">',
'            <td class="input_lable">',
'                <label>${item.label}</label>',
'            </td>',
'            <td class="input_box">',
'        {{if item.type=="select"}}',
'                <select name="${item.name.toLowerCase()}"{{if item.isDisabled}} disabled="disabled"{{/if}} class="input_${item.type}{{if item.aClass}} input_item_${item.type}_${item.aClass}{{/if}}" id="${guid}_input_${item.name.toLowerCase()}">',
'                    {{each(di,d) item.datas}}',
'        {{if d.t=="optgroup"}}',
'                    <optgroup label="${d.v}"></optgroup>',
'        {{else}}',
'                    <option value="${d.v}"{{if d.def || item.def==d.v}}selected="selected"{{/if}}>${d.t}</option>',
'        {{/if}}',
'                    {{/each}}',
'                </select>',
'        {{else item.type=="string"}}',
'                {{html htmlData}}',
'        {{else item.type=="radio"}}',
'                {{each(di,d) item.datas}}',
'                <input type="radio" name="${item.name.toLowerCase()}"{{if item.isDisabled}} disabled="disabled"{{/if}} value="${d.v}" {{if d.def}}checked="checked"{{/if}} class="input_${item.type}" id="${guid}_input_${item.name.toLowerCase()}_${d.v}" /><span class="radio_tip">${d.t}</span>',
'                {{/each}}',
'        {{else item.type=="checkbox"}}',
'                {{each(di,d) item.datas}}',
'                <input type="checkbox" name="${item.name.toLowerCase()}"{{if item.isDisabled}} disabled="disabled"{{/if}} value="${d.v}" {{if d.def}}checked="checked"{{/if}} class="input_${item.type}" id="${guid}_input_${item.name.toLowerCase()}_${d.v}" /><span class="checkbox_tip">${d.t}</span>',
'                {{/each}}',
'        {{else item.type=="textarea"}}',
'                <textarea name="${item.name.toLowerCase()}"{{if item.isDisabled}} disabled="disabled"{{/if}}{{if item.placeholder}} placeholder="${item.placeholder}"{{/if}}{{if item.isReadonly}} readonly="readonly"{{/if}} class="input_${item.type}{{if item.aClass}} input_${item.aClass}{{/if}}" id="${guid}_input_${item.name.toLowerCase()}">{{if item.def}}${item.def}{{/if}}</textarea>',
'        {{else item.type=="hidden" && item.aClass=="file"}}',
'                <input type="input_text" name="${item.name.toLowerCase()}"{{if item.placeholder}} placeholder="${item.placeholder}"{{/if}}{{if item.required}} required="required"{{/if}}{{if item.pattern}} pattern="${item.pattern}"{{/if}}{{if item.title}} title="${item.title}"{{/if}}{{if item.isDisabled}} disabled="disabled"{{/if}}{{if item.isReadonly}} readonly="readonly"{{/if}} class="input_${item.type} input_text{{if item.aClass}} input_${item.aClass}{{/if}}" id="${guid}_input_${item.name.toLowerCase()}"{{if item.def}} value="${item.def}"{{/if}} />',
'        {{else}}',
'                <input type="${item.type}" name="${item.name.toLowerCase()}"{{if item.placeholder}} placeholder="${item.placeholder}"{{/if}}{{if item.required}} required="required"{{/if}}{{if item.pattern}} pattern="${item.pattern}"{{/if}}{{if item.title}} title="${item.title}"{{/if}}{{if item.isDisabled}} disabled="disabled"{{/if}}{{if item.isReadonly}} readonly="readonly"{{/if}} class="input_${item.type}{{if item.aClass}} input_${item.aClass}{{/if}}" id="${guid}_input_${item.name.toLowerCase()}"{{if item.def}} value="${item.def}"{{/if}} />',
'        {{/if}}',
'        {{if item.uploader}}',
'                <input type="hidden" name="uploader_${item.name.toLowerCase()}" id="${guid}_uploader_${name}" class="uploader uploader_${item.type}{{if item.aClass}} uploader_${item.aClass}{{/if}}" for="${guid}_input_${item.name.toLowerCase()}" />',
'        {{/if}}',
'            </td>',
'            <td class="input_tip">',
'                {{if tip}}<img src="' + UI.BlankImg + '" title="${tip}" class="picon picon_{{if item.tipicon}}${tipicon}{{else}}information{{/if}}" />{{/if}}',
'            </td>',
'        </table>',
'        {{/if}}',
'        {{/each}}',
'   </div>',
'   {{if btns}}',
'   <div class="btns clearfix">',
'        {{each(index, btn) btns}}',
'        <input type="${btn.type}" class="btn_${btn.type}" value="${btn.label}" />',
'        {{/each}}',
'   </div>',
'   {{/if}}',
'</form>'
].join('');
    $.template("form", _tempt_form);

    function TianvForm(data) {
        /// <summary>生成树形</summary>
        /// <param name="data">树形数据</param>

        this.data = data;
        this.$el = null;
        return this;
    }

    TianvForm.prototype =
    {
        Init: function () {
            var $this = this;
            var $el = $this.$el;

            for (var i = 0; i < formInit.length; i++) {
                var fn = formInit[i];
                fn($el);
            }
        },
        getTimeString: function (str) {
            return ("00"+ str).substr((''+ str).length);    
        },
        getTime: function (date, fmt){
            return date.getFullYear() + '-' + this.getTimeString(date.getMonth() + 1) + '-' + this.getTimeString(date.getDate()) + ' ' +
                this.getTimeString(date.getHours()) + ':' + this.getTimeString(date.getMinutes()) + ':' + this.getTimeString(date.getSeconds());
        },
        Show: function () {
            var $this = this;
            if ($this.data && $this.data.items) {
                $.each($this.data.items, function (key, item) {
                    if (item.def && item.def == '{now}') {
                        item.def = $this.getTime(new Date());
                    }
                })
            }
            var $el = $.tmpl("form", $this.data);
            $this.$el = $el;

            $this.Init();

            return $el;
        }
    };

    TianvUI.prototype.Form = {
        Create: function (data) {
            /// <summary>生成表单文档</summary>
            /// <param name="data">表单结构</param>

            var ui = new TianvForm(data);
            var $el = ui.Show();
            $el.data('ui', ui);
            return $el;
        },
        SetValues: function ($form, data) {
            /// <summary>设置表单输入框的值</summary>
            /// <param name="$el">表单</param>
            /// <param name="data">表单值</param>

            if (!data) return;
            $.each(data, function (name, value) {
                var $input = $form.find('[name=' + name.toLowerCase() + ']');
                if ($input.length <= 0) return;

                var tagType = $input.attr('type');
                if (tagType == 'checkbox' || tagType == 'radio') {
                    $input.each(function () {
                        var me = $(this);
                        if ((',' + value + ',').indexOf(',' + me.val() + ',') >= 0) {
                            me.attr('checked', 'checked');
                        }
                        else {
                            me.removeAttr('checked');
                        }
                    });
                }
                else {
                    $input.val(value);
                }
            });
        }
    };

    formDestroy.push(function ($form) { $form.hide(); });

    elementClearFns.push(function ($el) {
        $el.find('.actionForm').each(function () {
            var $form = $(this);
            for (var i = 0; i < formDestroy.length; i++) {
                var fn = formDestroy[i];
                fn($form);
            }
        });
    });

})(jQuery);



/* Tianv.UI.Form.Select.js */
(function ($) {

    var _tempt_form_select = [
'<div id="select_container">',
'   <div class="select_div" style="display: none;"><ul>',
'       {{each(index, op) ops}}',
'       <li v="${op.value}">${op.title}</li>',
'       {{/each}}',
'   </ul></div>',
'   <input type="text" name="__${name}" value="${text}" disableautocomplete="disableautocomplete" autocomplete="off" class="select_input" /><img src="' + UI.BlankImg + '" alt="" class="select_button" />',
'</div>'].join('');
    $.template("form_select", _tempt_form_select);

    function TianvFormSelect($select) {
        /// <summary>生成下拉框</summary>
        /// <param name="$select">待替换下拉框</param>

        this.$select = $select;

        this.$el = null;
        this.$div = null;
        this.$input = null;
        this.$button = null;
        this.data = null;
        return this;
    }

    TianvFormSelect.prototype =
    {
        ShowSelect: function (showAllLi) {
            var $this = this;
            var $select = $this.$select;

            var finded = 0;
            var me_val = $this.$select.val();
            if (showAllLi) $this.$div.find('li').show();

            $this.$div.find('li').each(function () {
                var $li = $(this);
                var li_text = $li.text();
                if (li_text.indexOf(me_val) >= 0) {
                    if (finded == 0) {
                        $li.addClass('selected');
                    }
                    else {
                        $li.removeClass('selected');
                    }
                    finded++;
                    if (!showAllLi) $li.show();
                }
                else {
                    $li.removeClass('selected');
                    if (!showAllLi) $li.hide();
                }
            });

            if (!showAllLi && finded <= 0) {
                $this.$div.hide();
                return;
            }

            $this.$div.fadeIn('fast');

            // Hide bindings
            setTimeout(function () { // Delay for Mozilla
                function hideDiv() {
                    $this.$div.hide();
                }
                $(document).one("click", hideDiv);
            }, 0);
        },
        SetValue: function () {
            var $this = this;
            var $select = $this.$select;

            var $li = $this.$div.find('li.selected');
            if ($li.length <= 0) return;

            $select.val($li.attr('v'));
            $this.$input.val($li.text());
            $this.$div.hide();
            $select.trigger('change');
        },
        GetSelectData: function () {
            var $this = this;
            var $select = $this.$select;

            var data = {
                name: $select.attr('name'),
                id: $select.attr('id'),
                value: $select.val(),
                text: '',
                ops: []
            };
            $select.find('option').each(function () {
                var $op = $(this);
                var op_val = $op.val();
                var op_text = $op.text();
                data.ops.push({ value: op_val, title: op_text });
                if (op_val.toString() == data.value.toString()) {
                    data.text = op_text;
                }
            });
            return data;
        },
        GetSelect: function () {
            var $this = this;
            var $select = $this.$select;

            var $el = $.tmpl("form_select", $this.data);
            var $button = $el.find('.select_button');
            var $input = $el.find('.select_input');
            var $div = $el.find('.select_div');

            $this.$el = $el;
            $this.$button = $button;
            $this.$input = $input;
            $this.$div = $div;

            $button.hover(function () {
                $el.addClass('hover');
            }, function () {
                $el.removeClass('hover');
            }).mouseup(function () {
                $input.focus();
                $this.ShowSelect(true);
            });

            $input.focus(function () {
                $el.addClass('down');
            }).blur(function () {
                $el.removeClass('down');
            }).keydown(function (key) {
                if (key.keyCode == 13) //enter
                    return false;
            }).keyup(function (key) {
                var me = $(this);
                var me_val = me.val();
                if (key.keyCode == 27) { //esc
                    $this.$div.hide();
                    return false;
                }
                else if (key.keyCode == 13) { //enter
                    if ($div.css('display') == 'none')
                        return false;
                    $this.SetValue();
                    return false;
                }
                else if (key.keyCode == 40) { //down
                    if ($div.css('display') == 'none')
                        return false;
                    var li = $div.find('li.selected');
                    if (li.length <= 0) return;
                    var lin = li;
                    while (true) {
                        lin = lin.next();
                        if (lin.length <= 0)
                            break;
                        if (lin.css('display') == 'none')
                            continue;
                        li.removeClass('selected');
                        lin.addClass('selected');
                        break;
                    }
                    return false;
                }
                else if (key.keyCode == 38) { //up
                    if ($div.css('display') == 'none')
                        return false;
                    var li = $div.find('li.selected');
                    if (li.length <= 0) return;
                    var lin = li;
                    while (true) {
                        lin = lin.prev();
                        if (lin.length <= 0)
                            break;
                        if (lin.css('display') == 'none')
                            continue;
                        li.removeClass('selected');
                        lin.addClass('selected');
                        break;
                    }
                    return false;
                }

                $this.ShowSelect(false);
            });

            $div.find('li').hover(function () {
                $(this).addClass('hover');
            }, function () {
                $(this).removeClass('hover');
            }).click(function () {
                var me = $(this);
                $div.find('li.selected').removeClass('selected');
                me.addClass('selected');
                $this.SetValue();
            });

            return $el;
        },
        Replace: function () {
            var $this = this;
            var $select = $this.$select;
            var width = $select.width();
            $select.hide();

            $this.data = $this.GetSelectData();

            var $el = $this.GetSelect();
            $el.insertAfter($select);

            //$this.$input.width(width - 40); //14 17
            //$this.$div.width(width);

            $this.$el = $el;
            return $el;
        }
    };

    TianvUI.prototype.FormSelect = {
        Replace: function ($select) {
            /// <summary>生成表单文档</summary>
            /// <param name="data">表单结构</param>

            var ui = new TianvFormSelect($select);
            var $el = ui.Replace();
            $el.data('ui', ui);
            return $el;
        }
    };

    formInit.push(function ($form) {
        $form.find('select').each(function () {
            var $select = $(this);
            if (!$select.hasClass('input_item_select_noreplace')) {
                setTimeout(function () { UI.FormSelect.Replace($select) }, 20);
            }
        });
    });
})(jQuery);

/* Tianv.UI.FileShow.js */
(function ($) {

    var _tempt_fileShow = [
'{{if ex=="bmp" || ex=="jpg" || ex=="jpeg" || ex=="gif" || ex=="png" || ex=="ico"}}',
'<img src="${src}" alt="{{if alt}}${alt}{{/if}}" border="0" {{html exr}} />',
'{{else ex=="swf"}}',
'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" {{html exr}} codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0">',
'    <param name="src" value="${src}" />',
'    <embed type="application/x-shockwave-flash" {{html exr}} src="${src}"></embed>',
'</object>',
'{{else ex=="wma"}}',
'<object classid="clsid:6bf52a52-394a-11d3-b153-00c04f79faa6" {{html exr}} codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701">',
'    <param name="url" value="${src}" />',
'    <embed type="application/x-mplayer2" {{html exr}} src="${src}"></embed>',
'</object>',
'{{else ex=="mp3"}}',
'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" {{html exr}} codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0">',
'    <param name="bgcolor" value="#ffffff" />',
'    <param name="flashvars" value="file=${src}" />',
'    <param name="src" value="' + Conf.Paths.Admin + 'ui/swf/mp3player.swf?file=${src}" />',
'    <embed type="application/x-shockwave-flash" {{html exr}} src="' + Conf.Paths.Admin + 'ui/swf/mp3player.swf?file=${src}" flashvars="file=${src}" bgcolor="#ffffff"></embed>',
'</object>',
'{{else ex=="flv"}}',
'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" {{html exr}} codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0">',
'    <param name="src" value="' + Conf.Paths.Admin + 'ui/swf/flvplayer.swf?file=${src}&image=${src}.jpg" />',
'    <param name="allowfullscreen" value="true" />',
'    <embed type="application/x-shockwave-flash" {{html exr}} src="' + Conf.Paths.Admin + 'ui/swf/flvplayer.swf?file=${src}&image=${src}.jpg"></embed>',
'</object>',
'{{else ex=="rmvb" || ex=="rm"}}',
'<object classid="clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa" {{html exr}} codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0">',
'    <param name="src" value="${src}" />',
'    <embed type="audio/x-pn-realaudio-plugin" {{html exr}} src="${src}"></embed>',
'</object>',
'{{else ex=="mpg" || ex=="mpeg" || ex=="avi" || ex=="asf" || ex=="wmv" || ex=="mp4"}}',
'<object classid="clsid:6bf52a52-394a-11d3-b153-00c04f79faa6" {{html exr}} codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701">',
'    <param name="url" value="${src}" />',
'    <embed type="application/x-mplayer2" {{html exr}} src="${src}"></embed>',
'</object>',
'{{else ex=="mov"}}',
'<object classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b" {{html exr}} codebase="http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0">',
'    <param name="src" value="${src}" />',
'    <embed type="video/quicktime" {{html exr}} src="${src}"></embed>',
'</object>',
'{{else}}',
'<a href="${src}" target="_blank">${src}</a>',
'{{/if}}'
].join('');

    $.template("fileShow", _tempt_fileShow);

    function TianvFileShow() {
        return this;
    }

    TianvFileShow.prototype =
    {
        getExtension: function (file) {
            return file.indexOf('.') < 0 ? '' : file.substr(file.lastIndexOf('.') + 1);
        },
        getSize: function (ex) {
            if (ex == "bmp" || ex == "jpg" || ex == "jpeg" || ex == "gif" || ex == "png")
                return { width: 0, height: 0 };
            if (ex == "swf")
                return { width: 0, height: 0 };
            else if (ex == "wma")
                return { width: 320, height: 45 };
            else if (ex == "mp3")
                return { width: 320, height: 20 };
            else if (ex == "flv")
                return { width: 293, height: 240 };
            if (ex == "rmvb" || ex == "rm")
                return { width: 320, height: 280 };
            else if (ex == "rmvb" || ex == "rm")
                return { width: 320, height: 280 };
            else if (ex == "mpg" || ex == "mpeg" || ex == "avi" || ex == "asf" || ex == "wmv" || ex == "mp4")
                return { width: 320, height: 280 };
            else if (ex == "mov")
                return { width: 320, height: 280 };
            else
                return { width: 0, height: 0 };
        },
        getSizeStr: function (ex) {
            var size = this.getSize(ex);
            if (size.width <= 0)
                return '';
            else
                return 'width="' + size.width + '" height="' + size.height + '"';
        },
        Show: function (file) {

            var ex = this.getExtension(file);
            var exr = this.getSizeStr(ex);
            return $.tmpl("fileShow", {
                src: file,
                ex: ex,
                exr: exr
            });
        }
    };

    var sf = new TianvFileShow();

    TianvUI.prototype.ShowFile = function (file) {

        return sf.Show(file);
    };

    TianvUI.prototype.ShowFileSize = function (file) {

        return sf.getSize(sf.getExtension(file));
    };

})(jQuery);



/* Tianv.UI.Form.Uploader.js */
(function ($) {

    var _tempt_uploader_noflash = [
'    <div class="beautyFile">',
'        <input type="file" class="beautyFileFile" name="${name}__filedata" id="${id}__filedata" />',
'        <input type="text" class="beautyFileInput" /><img src="' + UI.BlankImg + '" alt="" />',
'    </div>'].join('');

    var _tempt_uploader_flash = [
'    <div style="margin-left: 142px;"><table cellpadding="0" cellspacing="0" class="swfupload_container">',
'        <tr>',
'            <td class="swfupload_bar_container">',
'                <div class="swfupload_bar" id="${id}__swfupload_bar">',
'                    <div class="swfupload_bar_line"></div>',
'                    <div class="swfupload_bar_text">&nbsp;</div>',
'                    <input type="text" class="swfupload_bar_name" name="${name}__filename" />',
'                </div>',
'            </td>',
'            <td class="swfupload_btn_container">',
'                <div class="swfupload_btn" id="${id}__swfupload_btn">&nbsp;</div>',
'            </td>',
'            <td class="swfupload_preview_container">',
'                <div class="swfupload_preview" id="${id}__swfupload_preview">&nbsp;</div>',
'            </td>',
'        </tr>',
'    </table></div>'].join('');

    var _tempt_uploader_editor = [
'    <div><table cellpadding="0" cellspacing="0" class="swfupload_container">',
'        <tr>',
'            <td class="swfupload_bar_container">',
'                <div class="swfupload_bar" id="${id}__swfupload_bar">',
'                    <div class="swfupload_bar_line"></div>',
'                    <div class="swfupload_bar_text">&nbsp;</div>',
'                    <input type="text" class="swfupload_bar_name" name="${name}__filename" />',
'                </div>',
'            </td>',
'            <td class="swfupload_btn_container">',
'                <div class="swfupload_btn" id="${id}__swfupload_btn">select</div>',
'            </td>',
'        </tr>',
'    </table></div>'].join('');

    var _tempt_uploader_multifile = [
'    <div><div class="swfupload_preview swfupload_preview_multifile_container" id="${id}__swfupload_preview"></div>',
'    <table cellpadding="0" cellspacing="0" class="swfupload_container">',
'        <tr>',
'            <td class="swfupload_bar_container">',
'                <div class="swfupload_bar" id="${id}__swfupload_bar">',
'                    <div class="swfupload_bar_line"></div>',
'                    <div class="swfupload_bar_text">&nbsp;</div>',
'                    <input type="text" class="swfupload_bar_name" name="${name}__filename" />',
'                </div>',
'            </td>',
'            <td class="swfupload_btn_container">',
'                <div class="swfupload_btn" id="${id}__swfupload_btn">select</div>',
'            </td>',
'        </tr>',
'    </table></div>'].join('');
    $.template("uploader_noflash", _tempt_uploader_noflash);
    $.template("uploader_editor", _tempt_uploader_editor);
    $.template("uploader_flash", _tempt_uploader_flash);
    $.template("uploader_multifile", _tempt_uploader_multifile);

    function getCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
        return '';
    }


    var upload_progress = {
        showProgress: function (progressBar, text, percent) {
            var swfupload_bar_text = progressBar.find('.swfupload_bar_text');
            var swfupload_bar_line = progressBar.find('.swfupload_bar_line');
            if (percent <= 0) {
                progressBar.find('input').val('');
                progressBar.removeClass('swfupload_bar_error');
                swfupload_bar_line.show();
                swfupload_bar_text.show();
            }

            swfupload_bar_text.html(text);
            swfupload_bar_line.width(parseInt(percent * 1.48));
        },
        hideProgress: function (progressBar) {
            progressBar.find('.swfupload_bar_text').hide();
            progressBar.find('.swfupload_bar_line').hide();
        }
    }

    var upload_preview = {
        singleFile: {
            view: function (progressPreview, fileName) {
                upload_preview.singleFile.add(progressPreview, fileName);
            },
            add: function (progressPreview, fileName) {

                var exs = UI.ShowFileSize(fileName);
                if (exs.width <= -1) {
                    var html = '<a href="' + fileName + '" target="_blank">' + Utils.getIcon('link_go') + '</a>';
                    progressPreview.html(html);
                }
                else {
                    var ex = fileName.indexOf('.') < 0 ? '' : fileName.substr(fileName.lastIndexOf('.') + 1);
                    var preview_btn = $(Utils.getIcon('lightbulb')).css({ 'cursor': 'pointer' });
                    var container = preview_btn;
                    container.click(function () {

                        var htmlData = $('<div class="box_preview"></div>')
                            .css({ 'margin': '5px 0 0 5px', 'width': exs.width })
                            .append(UI.ShowFile(fileName));

                        var $el = UI.Box({
                            icon: 'information', title: lan.Box.Title.Preview,
                            width: (exs.width <= 0 ? 320 : exs.width) + 22, height: (exs.height <= 0 ? 240 : exs.height) + 62,
                            close: true,
                            refresh: false
                        });
                        var box = $el.data('ui');

                        box.showHtml(htmlData);

                        var bClose = UI.Button.Create('button', lan.Box.Close, function () { box.Close(); });
                        box.showButtons([bClose]);
                    });
                    progressPreview.html(container);
                }
            }
        },
        multiFile: {
            view: function () {
            },
            add: function (uploader, progressPreview, fileName, fileTitle) {
                var preview = $('<div class="preview_img"><img src="' + fileName + '" alt="" /><input type="hidden" class="preview_img_name" value="' + upload_utility.getFileName(fileName) + '" /><input type="hidden" class="preview_img_title" value="' + upload_utility.getFileTitle(fileTitle) + '" /></div>');
                preview.find('img').click(function () {

                    var $el = UI.Box({
                        icon: 'information',
                        title: lan.Uploader.FileBox.Title,
                        width: 320 + 22, height: 295 + 62,
                        close: true,
                        refresh: false
                    });
                    var box = $el.data('ui');

                    var htmlData = '<div class="prompt"><div class="prompt_img"><img src="' + fileName + '" alt="" /></div><div class="prompt_item"><span>' + Utils.getText('lan.Uploader.FileBox.FileName') + '</span> <input type="text" name="pname" /></div><div class="prompt_item"><span>' + Utils.getText('lan.Uploader.FileBox.FileTitle') + '</span> <input type="text" name="ptitle" /></div></div>'; //str + <br />                
                    box.showHtml(htmlData);

                    var img = $(this);
                    var name = preview.find('.preview_img_name').val();
                    var title = preview.find('.preview_img_title').val();
                    $el.find('input[name="pname"]').val(name);
                    $el.find('input[name="ptitle"]').val(title);

                    var bDelete = UI.Button.Create('button', lan.Method.Delete, function () {
                        preview.remove();
                        box.Close();
                        upload_utility.previewUpdate(uploader, progressPreview);
                    });
                    var bOk = UI.Button.Create('button', lan.Box.Ok, function () {
                        var name = $el.find('input[name="pname"]').val();
                        var title = $el.find('input[name="ptitle"]').val();
                        preview.find('input.preview_img_name').val(name);
                        preview.find('input.preview_img_title').val(title);
                        box.Close();
                        upload_utility.previewUpdate(uploader, progressPreview);
                    });
                    var bCancle = UI.Button.Create('button', lan.Box.Close, function () {
                        box.Close();
                    });
                    box.showButtons([bDelete, bCancle, bOk]);

                });
                preview.find('input').change(function () {
                    upload_utility.previewUpdate(uploader, progressPreview);
                });
                preview.find('input').keyup(function () {
                    upload_utility.previewUpdate(uploader, progressPreview);
                });
                progressPreview.append(preview);

                progressPreview.sortable({
                    stop: function (event, ui) {
                        upload_utility.previewUpdate(uploader, progressPreview);
                    }
                });
                progressPreview.disableSelection();
            }
        }
    }

    var upload_utility = {
        getFileName: function (filenameWithPath) {
            return filenameWithPath.substring(filenameWithPath.lastIndexOf('/') + 1)
        },
        getFileTitle: function (filenameWithPath) {
            if (filenameWithPath.indexOf('.') < 0) return filenameWithPath;
            return filenameWithPath.substring(0, filenameWithPath.lastIndexOf('.'))
        },
        showError: function (str, progressBar) {
            if (progressBar) {
                progressBar.find('.swfupload_bar_text').hide();
                progressBar.find('.swfupload_bar_line').hide();
                progressBar.addClass('swfupload_bar_error');
                progressBar.find('input').val(Utils.getText(str));
            }
            else {
                //alert(str);
            }
        },
        previewUpdate: function (uploader, previewContainer) {
            var v = '';
            previewContainer.find('.preview_img').each(function () {
                var me = $(this);
                var img_file = me.find('img');
                var img_file_name = me.find('.preview_img_name');
                var img_file_title = me.find('.preview_img_title');
                var temp_str = img_file.attr('src') + '|' + img_file_name.val() + '|' + img_file_title.val();
                if (v.length >= 1) v = v + '<---->' + temp_str;
                else v = temp_str;
            });
            uploader.val(v);
        }
    }


    var upload_handlers = {
        preLoad: function () {
            if (this.support.loading) return true;
            upload_utility.showError('lan.Uploader.Errors.Load.NOT_SUPPORT_LOADING');
            return false;
        },
        loadFailed: function () {
            upload_utility.showError('lan.Uploader.Errors.Load.LOAD_FAILED');
        },
        fileDialogStart: function () {
            this.cancelUpload();
        },
        fileQueued: function (file) {
        },
        fileQueueError: function (file, errorCode, message) {
            var errorString = '';
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    errorString = 'lan.Uploader.Errors.Queue.QUEUE_LIMIT_EXCEEDED';
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    errorString = 'lan.Uploader.Errors.Queue.FILE_EXCEEDS_SIZE_LIMIT';
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    errorString = 'lan.Uploader.Errors.Queue.ZERO_BYTE_FILE';
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    errorString = 'lan.Uploader.Errors.Queue.INVALID_FILETYPE';
                    break;
                default:
                    errorString = 'lan.Uploader.Errors.Queue.OTHER';
                    break;
            }

            try {
                upload_utility.showError(errorString, this.customSettings.progressBar);
            } catch (ex) {
                this.debug(ex);
            }
        },
        fileDialogComplete: function (numFilesSelected, numFilesQueued) {
            this.startUpload();
            this.customSettings.uploader.data('numFilesQueued', numFilesQueued);
        },
        uploadStart: function (file) {
            try {
                upload_progress.showProgress(this.customSettings.progressBar, '0%', 0);
            }
            catch (ex) { }
            return true;
        },
        uploadProgress: function (file, bytesLoaded, bytesTotal) {
            try {
                var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
                var bar_text = percent + '%';
                var FilesQueued_Nums = this.customSettings.uploader.data('numFilesQueued');
                if (FilesQueued_Nums > 1) {
                    bar_text = bar_text + '(' + (FilesQueued_Nums - this.getStats().files_queued + 1) + '/' + FilesQueued_Nums + ')'
                }
                upload_progress.showProgress(this.customSettings.progressBar, bar_text, percent);
            } catch (ex) {
                this.debug(ex);
            }
        },
        uploadError: function (file, errorCode, message) {
            var errorString = '';
            switch (errorCode) {
                case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
                    errorString = 'lan.Uploader.Errors.Upload.HTTP_ERROR';
                    break;
                case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
                    errorString = 'lan.Uploader.Errors.Upload.UPLOAD_FAILED';
                    break;
                case SWFUpload.UPLOAD_ERROR.IO_ERROR:
                    errorString = 'lan.Uploader.Errors.Upload.IO_ERROR';
                    break;
                case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
                    errorString = 'lan.Uploader.Errors.Upload.SECURITY_ERROR';
                    break;
                case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
                    errorString = 'lan.Uploader.Errors.Upload.UPLOAD_LIMIT_EXCEEDED';
                    break;
                case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
                    errorString = 'lan.Uploader.Errors.Upload.FILE_VALIDATION_FAILED';
                    break;
                case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
                    errorString = 'lan.Uploader.Errors.Upload.FILE_CANCELLED';
                    break;
                case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
                    errorString = 'lan.Uploader.Errors.Upload.UPLOAD_STOPPED';
                    break;
                default:
                    errorString = 'lan.Uploader.Errors.Upload.OTHER';
                    break;
            }

            try {
                upload_utility.showError(errorString, this.customSettings.progressBar);
            } catch (ex) {
                this.debug(ex);
            }
        },
        uploadSuccess: function (file, data) {
            var serverData = $.parseJSON(data);
            if (!serverData.success) {
                //upload_progress.hideProgress(this.customSettings.progressBar);
                upload_utility.showError(serverData.tip, this.customSettings.progressBar);
                return;
            }
            try {
                upload_progress.hideProgress(this.customSettings.progressBar);
                var progressPreview = this.customSettings.progressPreview;
                var uploader = this.customSettings.uploader;
                if (uploader.hasClass('input_multifile')) {
                    upload_preview.multiFile.add(uploader, progressPreview, serverData.str, file.name);
                    upload_utility.previewUpdate(uploader, progressPreview);
                }
                else if (uploader.hasClass('uploader_textarea')) {
                    var t = uploader.parent().find('>textarea');
                    if (t.length <= 0) uploader.parent().find('textarea.input_textarea');
                    if (t.length <= 0) uploader.parent().find('textarea');
                    var result = UI.ShowFile(serverData.str);
                    var result_container = $('<div />');
                    result_container.append(result);
                    $.Editor.InsertHtml(t, result_container.html());
                    //addEditorContent(t, result_container.html());
                }
                else {
                    upload_preview.singleFile.add(progressPreview, serverData.str);
                    uploader.val(serverData.str);
                    this.customSettings.progressBar.find('input').val(upload_utility.getFileName(serverData.str));
                }
            } catch (ex) {
                this.debug(ex);
            }
        },
        uploadComplete: function (file) {
            if (this.getStats().files_queued >= 1) {
                this.startUpload();
            }
            upload_progress.hideProgress(this.customSettings.progressBar);
        }
    };



})(jQuery);

/* Tianv.UI.Editor.js */
/*  Interface
$.extend({
    Editor: {
        Create: function (el) { },
        Destroy: function (el) { },
        Sync: function (el) { },
        InsertHtml: function (el, result) { }
    }
});
*/
(function ($) {

    var scriptFile;
    if (Config_Configs.Admin.Remote.Editor) {
        scriptFile = Conf.RemoteHost + '/editors/' + Config_Configs.Admin.Editor + ".js";
    }
    else {
        scriptFile = Conf.Paths.Remote + 'editors/' + Config_Configs.Admin.Editor + ".js";
    }

    $LAB.script(scriptFile);

    formInit.push(function ($form) {
        $LAB
            .script(scriptFile)
            .wait(function () {
                $form.find('.input_editor_mini, .input_editor').each(function () {
                    var $editor = $(this);
                    setTimeout(function () { $.Editor.Create($editor); }, 50);
                });
            });
    });

    formDestroy.push(function ($form) {
        $LAB
        .script(scriptFile)
        .wait(function () {
            $form.find('.input_editor_mini, .input_editor').each(function () {
                var $editor = $(this);
                $.Editor.Destroy($editor);
            });
        });
    });

})(jQuery);

/* Tianv.UI.GridSearch.js */
(function ($) {

    TianvUI.prototype.GridButtons = function (btns, grid) {
        /// <summary>生成Grid按钮</summary>

        if (!btns || btns.length <= 0)
            return;

        var $el = $('<ul class="b3"></ul>');
        for (var i = 0; i < btns.length; i++) {
            var btn = btns[i];
            var $bn = Utils.getSmallButton(btn, true, true);
            if (btn.postData) {
                btn.postData['items'] = grid.$el;
                //""items"": ""#frame_main input:checked[name=id]""
                $bn.data('postData', btn.postData);
            }
            $el.append($('<li />').append($bn));
        }
        return $el;
    };

    var _tempt_gridSearch = [
'<form class="t_search" method="post" action="#" target="_search">',
'{{each(index, item) sels}}',
'        {{if hide}}',
'        {{else}}',
'    <select name="${item.name}">',
'    <option value="">${item.title}</option>',
'    {{each(dindex, data) item.datas}}',
'        {{if data.t=="optgroup"}}',
'    <optgroup label="${data.v}"></optgroup>',
'        {{else}}',
'    <option value="${data.v}">${data.t}</option>',
'        {{/if}}',
'    {{/each}}',
'    </select>',
'        {{/if}}',
'{{/each}}',
'    <input type="submit" class="search_btn" value="' + lan.SearchBox.Search + '" />',
'    <input type="text" class="search_text" name="q" value="" />',
'</form>'
].join('');
    $.template("gridSearch", _tempt_gridSearch);

    TianvUI.prototype.GridSearch = function (datas, grid) {
        /// <summary>生成Grid搜索框</summary>

        var $el = $.tmpl('gridSearch', datas);

        //默认值
        var ps = {};
        var curl = grid.opts.dataUrl; // elements.frame.main.data('url');
        var cquery = (curl.indexOf('?') < 0) ? '' : curl.substr(curl.indexOf('?')).replace('?', '');
        var cquerys = cquery.split('&');
        for (var i = 0; i < cquerys.length; i++) {
            if (cquerys[i].indexOf('=') <= 0) {
                continue;
            }
            var n = cquerys[i].substr(0, cquerys[i].indexOf('='));
            var v = cquerys[i].substr(cquerys[i].indexOf('=')).replace('=', '');
            ps[n] = v;
        }

        //隐藏部分搜索框
        $el.find('select').each(function () {
            var me = $(this);
            var me_name = $(this).attr('name');
            $.each(ps, function (n, v) {
                if (n != me_name) return;
                me.attr('disabled', 'disabled').hide();
                me.val(v);
            });
        });

        //搜索
        $el.bind('submit', function () {
            var me = $(this);
            var me_data = me.serialize();

            grid.query = me_data;
            grid.pageIndex = 1;
            grid.Refresh();

            return false; // <-- important!
        });

        return $el;
    };

    var _tempt_gridToolBar = [
'<div class="tools">',
'    <div class="searchs">',
'    </div>',
'    <div class="buttons">',
'    </div>',
'</div>',
].join('');
    $.template("gridToolBar", _tempt_gridToolBar);

    TianvUI.prototype.GridToolbar = function (data, grid) {
        var $el = $.tmpl('gridToolBar', data);

        var $search = UI.GridSearch(data, grid);
        var $btns = UI.GridButtons(data.btns, grid);

        $el.children('.searchs').html($search);
        if ($btns) $el.children('.buttons').html($btns);

        return $el;
    };

})(jQuery);

/* Tianv.UI.GridPager.js */
(function ($) {

    var _tempt_gridPager = [
'            <div class="t_pager_btns">',
'        {{if pageIndex<=1}}',
'                <img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_first" />',
'                <img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_prev" />',
'        {{else}}',
'                <a href="javascript: void(0)"><img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_first" /></a>',
'                <a href="javascript: void(0)"><img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_prev" /></a>',
'        {{/if}}',
'                <img src="' + UI.BlankImg + '" class="pager_split" />',
'                <span class="t_pager_jumper"></span>',
'                <img src="' + UI.BlankImg + '" class="pager_split" />',
'        {{if pageIndex>=pageTotal}}',
'                <img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_next" />',
'                <img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_last" />',
'        {{else}}',
'                <a href="javascript: void(0)"><img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_next" /></a>',
'                <a href="javascript: void(0)"><img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_last" /></a>',
'        {{/if}}',
'                <img src="' + UI.BlankImg + '" class="pager_split" />',
'                <a href="javascript: void(0)"><img src="' + UI.BlankImg + '" class="t_pager_btn t_pager_refresh" /></a>',
'            </div>',
'            <div class="t_pager_text">',
'                <span>Displaying ${ItemsStart} - ${ItemsEnd} of ${ItemsCount}</span>',
'            </div>'
].join('');
    $.template("gridPager", _tempt_gridPager);

    function TianvGridPager(ItemsCount, pageSize, pageIndex, fnRefresh) {
        /// <summary>分页</summary>
        /// <param name="ItemsCount">总过?个</param>
        /// <param name="pageSize">每页?个</param>
        /// <param name="pageIndex">当前?页</param>
        /// <param name="fnRefresh">跳转方式</param>

        this.ItemsCount = ItemsCount;
        this.pageSize = pageSize;
        this.pageIndex = pageIndex;
        this.fnRefresh = fnRefresh;

        this.pageTotal = parseInt(ItemsCount / pageSize);
        if (this.pageTotal * pageSize < ItemsCount) this.pageTotal++;

        if (this.pageIndex > this.pageTotal) this.pageIndex = this.pageTotal;
        if (this.pageIndex == 0 && ItemsCount >= 1) this.pageIndex = 1;

        this.ItemsStart = Math.max(0, (pageIndex - 1) * pageSize + 1);
        this.ItemsEnd = Math.min(ItemsCount, this.pageIndex * pageSize);

        return this;
    }

    TianvGridPager.prototype =
    {
        getJumper: function () {
            var $this = this;

            var maxPage = Math.max(1, this.pageTotal);
            var strs = [];

            strs.push('<select name="pager" class="t_pager_jumper">');
            for (var i = 1; i <= maxPage; i++) {
                if (i == this.pageIndex) {
                    strs.push('<option value="' + i + '" selected="selected"> ' + i + ' / ' + maxPage + ' </option>');
                }
                else {
                    strs.push('<option value="' + i + '"> ' + i + ' / ' + maxPage + ' </option>');
                }
            }
            strs.push('</select>');
            return strs.join('');
        },
        Jump: function () {
            var $this = this;
            $this.fnRefresh($this);
        },
        Show: function () {
            var $this = this;

            var pager = $.tmpl('gridPager', $this);
            pager.find('.t_pager_refresh').click(function () {
                $this.Jump();
            });

            pager.find('a .t_pager_first').click(function () {
                $this.pageIndex = 1;
                $this.Jump();
            });
            pager.find('a .t_pager_prev').click(function () {
                $this.pageIndex--;
                $this.Jump();
            });
            pager.find('a .t_pager_next').click(function () {
                $this.pageIndex++;
                $this.Jump();
            });
            pager.find('a .t_pager_last').click(function () {
                $this.pageIndex = $this.pageTotal;
                $this.Jump();
            });

            var jumper = $($this.getJumper());
            jumper.change(function () {
                $this.pageIndex = $(this).val();
                $this.Jump();
            });
            pager.find('.t_pager_jumper').append(jumper);

            return pager;
        }
    }

    TianvUI.prototype.GridPager = function (ItemsCount, pageSize, pageIndex, fnRefresh) {
        /// <summary>生成Grid分页</summary>
        /// <param name="ItemsCount">总过?个</param>
        /// <param name="pageSize">每页?个</param>
        /// <param name="pageIndex">当前?页</param>
        /// <param name="fnRefresh">跳转方式</param>

        var ui = new TianvGridPager(ItemsCount, pageSize, pageIndex, fnRefresh);
        var $el = ui.Show();
        $el.data('ui', ui);
        return $el;
    };

})(jQuery);

/* Tianv.UI.Grid.js */
function get_ColumnView(column) {
    if (column.view == undefined || column.view == 'text')
        return '<div>${' + column.name + '}</div>';
    else
        return column.view;
}

(function ($) {

    var _tempt_grid = [
'    <div class="t_grid">',
'        <div class="t_search">',
'        </div>',
'        <div class="t_button">',
'        </div>',
'        <div class="t_container">',
'            <div class="t_header">',
'                <table cellpadding="0" cellspacing="0">',
'                    <tr class="row_1">',
'                        <td class="col_checkbox col_0"><input type="checkbox" class="checkbox checkAll" /></td>',
'                    {{each(columnIndex, column) columns}}',
'                        <td class="col_${name} col_${columnIndex+1}"><div><label for="${name}">${title}</label>{{if sortAble}}<img src="' + UI.BlankImg + '" alt="" class="corder" />{{/if}}</div></td>',
'                    {{/each}}',
'                    </tr>',
'                </table>',
'            </div>',
'            <div class="t_body">&nbsp;</div>',
'            <div class="t_footer">',
'                <table cellpadding="0" cellspacing="0">',
'                    <tr class="row_1">',
'                        <td class="col_checkbox col_0">&nbsp;</td>',
'                    {{each(columnIndex, column) columns}}',
'                        <td class="col_${name} col_${columnIndex+1}">&nbsp;</td>',
'                    {{/each}}',
'                    </tr>',
'                </table>',
'            </div>',
'        </div>',
'        {{if pager}}',
'        <div class="t_pager">&nbsp;</div>',
'        {{/if}}',
'    </div>'
].join('');
    $.template("grid", _tempt_grid);

    var _tempt_grid_body = [
'                <table cellpadding="0" cellspacing="0">',
'                    {{each(rowIndex, row) gridData.rows}}',
'                    <tr class="row_${rowIndex+1} {{if rowIndex%2==0}}odd{{else}}even{{/if}}">',
'                        <td class="col_checkbox col_0"><input type="checkbox" class="checkbox" name="id" value="${row.id}" /></td>',
'                    {{each(columnIndex, column) gridSetting.columns}}',
'                        <td class="col_${name} col_${columnIndex+1}">{{tmpl(row) get_ColumnView(column)}} </td>',
'                    {{/each}}',
'                    </tr>',
'                    {{/each}}',
'                </table>'
].join('');
    $.template("gridBody", _tempt_grid_body);

    var t_html_loading = '<div class="t_loading"><img src="' + UI.BasePath + 'view/grid/loading.gif" alt="" /><span title="lan.Grid.Loading"><span></div>';
    var t_html_nodata = '<div class="t_nodata"><span title="lan.Grid.NoData"><span></div>';
    function get_html_error(xhr, ajaxOptions, thrownError) {
        return '<div class="t_error">' + Utils.getText('lan.Ajax.Error.E' + xhr.status) + '</div>'
    };

    var t_grid_const_data = {
        scrollbar_width: 16,
        search_height: 27,
        pager_height: 27,
        head_height: 24,
        foot_height: 9
    };

    //默认选项 
    var defaultSettings = {
        checkbox: true,
        pager: true,
        pageSize: 20,
        dataUrl: null,
        data: null,
        search: null,
        pagesizes: [10, 20, 50, 100, 200, 500],
        sort: { name: 'id', order: 'desc' },
        width: 480,
        height: 320
    };

    function TianvGrid(settings, width, height) {
        /// <summary>生成树形</summary>
        /// <param name="data">树形数据</param>

        this.opts = $.extend({}, defaultSettings, settings || {});

        this.guid = Utils.getGuid();

        this.width = width;
        this.height = height;

        this.$container = null;
        this.$header = null;
        this.$body = null;
        this.$footer = null;
        this.$pager = null;
        this.$el = null;

        this.pageIndex = 1;
        this.data = null ;
        if( this.opts.data != null )        this.data = this.opts.data;
        this.query = null;

        return this;
    }
    TianvGrid.prototype =
    {
        Select: function ($tr, checked) {
            var checkbox = $tr.find(':checkbox');
            if (checked) {
                if (!$tr.hasClass('selected')) $tr.addClass('selected');
                if (!checkbox.attr('checked')) checkbox.attr('checked', 'checked');
            }
            else {
                $tr.removeClass('selected');
                checkbox.removeAttr('checked');
            }
        },
        Resize: function () {
            var $this = this;

            $this.$el.width($this.width);
            $this.$container.width($this.width);
            $this.$el.find('table').width($this.width - t_grid_const_data.scrollbar_width);

            var body_height = $this.height - 
                ($this.opts.search? t_grid_const_data.search_height: 0) - 
                t_grid_const_data.head_height - 
                t_grid_const_data.foot_height - 
                ($this.opts.pager ? t_grid_const_data.pager_height : 0);
            $this.$body.height(body_height);
        },
        ShowLoading: function () {
            var $this = this;
            var $loading = $( t_html_loading);
            Utils.setText( $loading);
            $this.$body.html( $loading);
        },
        ShowNodata: function() {
            var $this = this;
            var $nodata = $( t_html_nodata);
            Utils.setText( $nodata );
            $this.$body.html($nodata );
        },
        ShowError: function(xhr, ajaxOptions, thrownError) {
            var $this = this;
            $this.$body.html(get_html_error(xhr, ajaxOptions, thrownError));
        },
        ShowData: function () {
            var $this = this;

            if( $this.data.count <= 0 )            {
                $this.ShowNodata( );
                return;
            }
            else{
                if ($this.opts.pager) {
                    var $pager = UI.GridPager($this.data.count, $this.opts.pageSize, $this.pageIndex, function (pager) { $this.pageIndex = pager.pageIndex;; $this.Refresh(); });
                    $this.$pager.html($pager);
                }
            }

            var body = $.tmpl('gridBody', {
                gridData: $this.data,
                gridSetting: $this.opts,
                UI: UI
            });
            
            body.width($this.$header.find('table').width()); 
            $this.setColumnWidth( body, $this.opts.columns );
            $this.$body.html(body);

            /* 行点击 选择/取消选择 */
            $this.$body.find('td').click(function () {
                var $me = $(this);
                if ($me.find('input').length >= 1 || $me.find('a').length >= 1) return;
                var $tr = $me.parent();
                $this.Select($tr, !$tr.hasClass('selected'));
            });
            /* checkbox点击 选择/取消选择 */
            $this.$body.find(':checkbox').change(function () {
                var $me = $(this);
                var checked = $me.attr('checked');
                var $tr = $me.parent().parent();
                $this.Select($tr, checked);
            });
        },
        Refresh: function () {

            var $this = this;
            
            $this.$header.find(':checkbox').removeAttr('checked');

            $this.ShowLoading();

            if ($this.opts.dataUrl) {
                var parm_page = 'pageIndex=' + Math.max(1, $this.pageIndex) + '&pageSize=' + $this.opts.pageSize;//
                var parm_sort = 'sortName=' + $this.opts.sort.name + '&sortOrder=' + $this.opts.sort.order;
                var parm_search = '';
                if ($this.opts.search && $this.opts.search.length >= 1) {
                    parm_search = '&' + $this.opts.search;
                }
                var parms = [parm_page, parm_sort, parm_search].join('&');
                if( $this.query )
                    parms = (parms + '&'+ $this.query).replace('&&', '&');

                $.ajax({
                    url: $this.opts.dataUrl,
                    dataType: 'json',
                    data: parms,
                    success: function (data) {
                        if (data.count === undefined) return;
                        $this.data = data;
                        $this.ShowData();
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $this.ShowError( xhr, ajaxOptions, thrownError ); 
                    }
                });
            }
            else if ($this.data) {
                $this.ShowData();
            }
        },
        setColumnWidth: function($el, columns){
            for (var i = 0; i < columns.length; i++) {
                var column = columns[i];
                if (column.width) {
                    $el.find('td.col_' + (i + 1)).width(column.width);
                }
                if (column.align) {
                    $el.find('td.col_' + (i + 1)).css('text-align', column.align);
                }
            }
        },
        Show: function () {
            var $this = this;

            var $el = $.tmpl('grid', $this.opts);

            $this.$el = $el;
            $this.$container = $el.find(".t_container");
            $this.$header = $el.find(".t_header");
            $this.$body = $el.find(".t_body");
            $this.$footer = $el.find(".t_footer");
            $this.$pager = $el.find(".t_pager");
            $this.$buttons = $el.find(".t_button");
            
            //buttons
            if( $this.opts.search){
                var $tool = UI.GridToolbar( $this.opts.search, $this );
                    $el.prepend( $tool );
            }
            
            if ($this.height <= 0 || $this.width<=0) {
                $el.css('visibility', 'hidden');
                UI.AutoResizeAble($el, function (w, h) {
                    $this.width = w;// $parent.width();
                    $this.height = h;// $parent.height();
                    $this.Resize();
                    $el.css('visibility', 'visible');
                });
            }
            else {
                $this.Resize();
            }

            /* 栏目宽度 */
            $this.setColumnWidth( $el, $this.opts.columns );

            /* checkall点击 全选/取消选择 */
            $this.$header.find(':checkbox').click(function () {
                var $me = $(this);
                var checked = $me.attr('checked');
                $this.$body.find('tr').each(function () {
                    $this.Select($(this), checked);
                });
            });

            /* 排序 */
            $this.$header.find('div:has(img.corder)').click(function () {
                var $me = $(this);
                var $img = $me.find('img');
                $this.opts.sort.name = $me.find('label').attr('for');
                if (!$img.hasClass('corder_desc')) {
                    $this.$header.find('img.corder').removeClass('corder_asc').removeClass('corder_desc');
                    $img.addClass('corder_desc');
                    $this.opts.sort.order = 'desc';
                }
                else {
                    $this.$header.find('img.corder').removeClass('corder_asc').removeClass('corder_desc');
                    $img.addClass('corder_asc');
                    $this.opts.sort.order = 'asc';
                }
                $this.pageIndex = 1;
                $this.Refresh();
            });

            $this.Refresh();

            return $el;
        }
    };

    TianvUI.prototype.Grid = function (data, width, height) {
        /// <summary>生成表格</summary>
        /// <param name="width">表格宽度</param>
        /// <param name="height">表格高度</param>

        var w = 0;
        if (Utils.isNumber(width) && width >= 1) w = width;

        var h = 0;
        if (Utils.isNumber(height) && height >= 1) h = height;

        var ui = new TianvGrid(data, w, h);
        var $el = ui.Show();
        $el.data('ui', ui);

        return $el;
    };

})(jQuery);

/* Tianv.UI.GridImage.js */
function get_ColumnDealView(column) {
    if (column.view && column.name == 'deal')
        return column.view;
    else
        return '';
}


(function ($) {

    var _tempt_grid = [
'    <div class="t_grid i_grid">',
'        <div class="t_search">',
'        </div>',
'        <div class="t_button">',
'        </div>',
'        <div class="t_container">',
'            <div class="t_header">',
'                <table cellpadding="0" cellspacing="0">',
'                    <tr class="row_1">',
'                        <td class="col_checkbox col_0"><input type="checkbox" class="checkbox checkAll" /></td>',
'                    {{each(columnIndex, column) columns}}',
'                        <td class="col_${name} col_${columnIndex+1}"><div><label for="${name}">${title}</label>{{if sortAble}}<img src="' + UI.BlankImg + '" alt="" class="corder" />{{/if}}</div></td>',
'                    {{/each}}',
'                    </tr>',
'                </table>',
'            </div>',
'            <div class="t_body">&nbsp;</div>',
'            <div class="t_footer">',
'                <table cellpadding="0" cellspacing="0">',
'                    <tr class="row_1">',
'                        <td class="col_checkbox col_0">&nbsp;</td>',
'                    {{each(columnIndex, column) columns}}',
'                        <td class="col_${name} col_${columnIndex+1}">&nbsp;</td>',
'                    {{/each}}',
'                    </tr>',
'                </table>',
'            </div>',
'        </div>',
'        {{if pager}}',
'        <div class="t_pager">&nbsp;</div>',
'        {{/if}}',
'    </div>'
].join('');
    $.template("igrid", _tempt_grid);

    var _tempt_grid_body = [
'                <ul>',
'                    {{each(rowIndex, row) gridData.rows}}',
'                    <li class="i_grid_li rad3">',
'                        <div class="i_grid_item">',
'                           <div class="i_grid_item_imgc"{{if height}} style="height: ${height + 2}px;"{{/if}}><img class="i_grid_item_imgc_img" src="${pic}" alt="" /></div>',
'                           <div class="i_grid_item_title">${title}</div>',
'                           <div class="i_grid_item_icons">',
'                               {{tmpl(row) get_ColumnDealView(gridSetting.columns[2])}}',
'                           </div>',
'                        </div>',
'                    </li>',
'                    {{/each}}',
'                </ul>'
].join('');
    $.template("igridBody", _tempt_grid_body);

    //{{each(columnIndex, column) gridSetting.columns}}{{/each}}

    var t_html_loading = '<div class="t_loading"><img src="' + UI.BasePath + 'view/grid/loading.gif" alt="" /><span title="lan.Grid.Loading"><span></div>';
    var t_html_nodata = '<div class="t_nodata"><span title="lan.Grid.NoData"><span></div>';
    function get_html_error(xhr, ajaxOptions, thrownError) {
        return '<div class="t_error">' + Utils.getText('lan.Ajax.Error.E' + xhr.status) + '</div>'
    };

    var t_grid_const_data = {
        scrollbar_width: 16,
        search_height: 27,
        pager_height: 27,
        head_height: 24,
        foot_height: 9
    };

    //默认选项 
    var defaultSettings = {
        checkbox: true,
        pager: true,
        pageSize: 20,
        dataUrl: null,
        data: null,
        search: null,
        pagesizes: [10, 20, 50, 100, 200, 500],
        sort: { name: 'id', order: 'desc' },
        width: 480,
        height: 320
    };

    function TianvGrid(settings, width, height) {
        /// <summary>生成树形</summary>
        /// <param name="data">树形数据</param>

        this.opts = $.extend({}, defaultSettings, settings || {});

        this.guid = Utils.getGuid();

        this.width = width;
        this.height = height;

        this.$container = null;
        this.$header = null;
        this.$body = null;
        this.$footer = null;
        this.$pager = null;
        this.$el = null;

        this.pageIndex = 1;
        this.data = null ;
        if( this.opts.data != null )        this.data = this.opts.data;
        this.query = null;

        return this;
    }
    TianvGrid.prototype =
    {
        Select: function ($tr, checked) {
            var checkbox = $tr.find(':checkbox');
            if (checked) {
                if (!$tr.hasClass('selected')) $tr.addClass('selected');
                if (!checkbox.attr('checked')) checkbox.attr('checked', 'checked');
            }
            else {
                $tr.removeClass('selected');
                checkbox.removeAttr('checked');
            }
        },
        Resize: function () {
            var $this = this;

            $this.$el.width($this.width);
            $this.$container.width($this.width);
            $this.$el.find('table').width($this.width - t_grid_const_data.scrollbar_width);

            var body_height = $this.height - 
                ($this.opts.search? t_grid_const_data.search_height: 0) - 
                t_grid_const_data.head_height - 
                t_grid_const_data.foot_height - 
                ($this.opts.pager ? t_grid_const_data.pager_height : 0);
            $this.$body.height(body_height);
        },
        ShowLoading: function () {
            var $this = this;
            var $loading = $( t_html_loading);
            Utils.setText( $loading);
            $this.$body.html( $loading);
        },
        ShowNodata: function() {
            var $this = this;
            var $nodata = $( t_html_nodata);
            Utils.setText( $nodata );
            $this.$body.html($nodata );
        },
        ShowError: function(xhr, ajaxOptions, thrownError) {
            var $this = this;
            $this.$body.html(get_html_error(xhr, ajaxOptions, thrownError));
        },
        ShowData: function () {
            var $this = this;

            if( $this.data.count <= 0 )            {
                $this.ShowNodata( );
                return;
            }
            else{
                if ($this.opts.pager) {
                    var $pager = UI.GridPager($this.data.count, $this.opts.pageSize, $this.pageIndex, function (pager) { $this.pageIndex = pager.pageIndex;; $this.Refresh(); });
                    $this.$pager.html($pager);
                }
            }

            var body = $.tmpl('igridBody', {
                gridData: $this.data,
                gridSetting: $this.opts,
                UI: UI
            });
            
            //body.width($this.$header.find('table').width()); 
            $this.setColumnWidth( body, $this.opts.columns );
            $this.$body.html(body);

            /* 行点击 选择/取消选择 */
            $this.$body.find('td').click(function () {
                var $me = $(this);
                if ($me.find('input').length >= 1 || $me.find('a').length >= 1) return;
                var $tr = $me.parent();
                $this.Select($tr, !$tr.hasClass('selected'));
            });
            /* checkbox点击 选择/取消选择 */
            $this.$body.find(':checkbox').change(function () {
                var $me = $(this);
                var checked = $me.attr('checked');
                var $tr = $me.parent().parent();
                $this.Select($tr, checked);
            });
        },
        Refresh: function () {

            var $this = this;
            
            $this.$header.find(':checkbox').removeAttr('checked');

            $this.ShowLoading();

            if ($this.opts.dataUrl) {
                var parm_page = 'pageIndex=' + Math.max(1, $this.pageIndex) + '&pageSize=' + $this.opts.pageSize;//
                var parm_sort = 'sortName=' + $this.opts.sort.name + '&sortOrder=' + $this.opts.sort.order;
                var parm_search = '';
                if ($this.opts.search && $this.opts.search.length >= 1) {
                    parm_search = '&' + $this.opts.search;
                }
                var parms = [parm_page, parm_sort, parm_search].join('&');
                if( $this.query )
                    parms = (parms + '&'+ $this.query).replace('&&', '&');

                $.ajax({
                    url: $this.opts.dataUrl,
                    dataType: 'json',
                    data: parms,
                    success: function (data) {
                        if (data.count === undefined) return;
                        $this.data = data;
                        $this.ShowData();
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        $this.ShowError( xhr, ajaxOptions, thrownError ); 
                    }
                });
            }
            else if ($this.data) {
                $this.ShowData();
            }
        },
        setColumnWidth: function($el, columns){
            for (var i = 0; i < columns.length; i++) {
                var column = columns[i];
                if (column.width) {
                    $el.find('td.col_' + (i + 1)).width(column.width);
                }
                if (column.align) {
                    $el.find('td.col_' + (i + 1)).css('text-align', column.align);
                }
            }
        },
        Show: function () {
            var $this = this;

            var $el = $.tmpl('igrid', $this.opts);

            $this.$el = $el;
            $this.$container = $el.find(".t_container");
            $this.$header = $el.find(".t_header");
            $this.$body = $el.find(".t_body");
            $this.$footer = $el.find(".t_footer");
            $this.$pager = $el.find(".t_pager");
            $this.$buttons = $el.find(".t_button");
            
            //buttons
            if( $this.opts.search){
                var $tool = UI.GridToolbar( $this.opts.search, $this );
                    $el.prepend( $tool );
            }
            
            if ($this.height <= 0 || $this.width<=0) {
                $el.css('visibility', 'hidden');
                UI.AutoResizeAble($el, function (w, h) {
                    $this.width = w;// $parent.width();
                    $this.height = h;// $parent.height();
                    $this.Resize();
                    $el.css('visibility', 'visible');
                });
            }
            else {
                $this.Resize();
            }

            /* 栏目宽度 */
            $this.setColumnWidth( $el, $this.opts.columns );

            /* checkall点击 全选/取消选择 */
            $this.$header.find(':checkbox').click(function () {
                var $me = $(this);
                var checked = $me.attr('checked');
                $this.$body.find('tr').each(function () {
                    $this.Select($(this), checked);
                });
            });

            /* 排序 */
            $this.$header.find('div:has(img.corder)').click(function () {
                var $me = $(this);
                var $img = $me.find('img');
                $this.opts.sort.name = $me.find('label').attr('for');
                if (!$img.hasClass('corder_desc')) {
                    $this.$header.find('img.corder').removeClass('corder_asc').removeClass('corder_desc');
                    $img.addClass('corder_desc');
                    $this.opts.sort.order = 'desc';
                }
                else {
                    $this.$header.find('img.corder').removeClass('corder_asc').removeClass('corder_desc');
                    $img.addClass('corder_asc');
                    $this.opts.sort.order = 'asc';
                }
                $this.pageIndex = 1;
                $this.Refresh();
            });

            $this.Refresh();

            return $el;
        }
    };

    TianvUI.prototype.GridImage = function (data, width, height) {
        /// <summary>生成表格</summary>
        /// <param name="width">表格宽度</param>
        /// <param name="height">表格高度</param>

        var w = 0;
        if (Utils.isNumber(width) && width >= 1) w = width;

        var h = 0;
        if (Utils.isNumber(height) && height >= 1) h = height;

        var ui = new TianvGrid(data, w, h);
        var $el = ui.Show();
        $el.data('ui', ui);

        return $el;
    };

})(jQuery);

/* Tianv.UI.Views.js */
function TianvPageView() { return this; }
function TianvBoxView() { return this; }

var Views = {
    Page: new TianvPageView(),
    Box: new TianvBoxView()
};

(function ($) {

    var loading = '<div class="frame_main_loading"><img src="/admin/ui/images/main_loading.gif" alt="" /><span>' + lan.Default.Loading + '<span></div>';

    TianvPageView.prototype.Load = function( url )    {
        /// <summary>加载页面</summary>

        var uname = Utils.getDirName(url);
        var sname = Utils.getSecondDirName( url );
        var lname = Utils.getLastDirName( url );

        var $container = elements.frame.main;
        UI.Clear($container);

        $container.html(loading);
        $container.data('url', url);

        var oaj = $container.data('ajax');
        if (oaj) oaj.abort();

        var aj = $.ajax({
            url: url,
            cache: false,
            success: function (data) {
                if( uname != null && uname.length>=1 ){
                    $container.html(data.replace('{uname}', uname ).replace('{sname}', sname ).replace('{lname}', lname ));
                }
                else{
                    $container.html(data);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                var errorString = Utils.getText('lan.Ajax.Error.E' + xhr.status);
                $container.html('<div class="frame_main_error">' + errorString + '</div>');
            }
        });
        $container.data('ajax', aj);
    };

    TianvPageView.prototype.ReflashMenu = function (){
        /// <summary>刷新左侧导航栏</summary>
        
        var $menu = elements.frame.left.children('.accordion');
        var $title = $menu.children('.active');
        $menu.data('ui').reload($title);
    };

    TianvPageView.prototype.ReflashData = function(){
        /// <summary>刷新列表</summary>
    
        var $grid = elements.frame.main.find('.t_grid');
        if ($grid.length >= 1) {
            $grid.data('ui').Refresh();
        }
    };

    TianvPageView.prototype.Reload = function(  )    {
        /// <summary>刷新页面</summary>

        var $container = elements.frame.main;
        var url = $container.data('url');
        this.Load( url );
    };

    TianvPageView.prototype.LoadData = function( url,query )    {
        /// <summary>加载页面</summary>

        var $container = elements.frame.main;

        var m_loading = $(loading);
        $container.append(m_loading);

        //数据读取
        var responseText = $.ajax({
            url: url,//            data: query,
            data: query,
            async: false,
            cache: false
        }).responseText;
        var obj = jQuery.parseJSON(responseText);

        if (typeof (obj.success) != 'undefined' && obj.success === false && obj.str != 'user') {
            UI.MessageBox.ShowError('error', obj.str, obj.str);
            return null;
        }

        if (obj && obj.success == false && obj.str == 'user') {
            return;
        }

        //数据检查
        //if (!checkLogin(obj)) return false;

        //end loading
        m_loading.remove();
        return obj;
    };

    function getTextBox(tid, size){
        /// <summary>生成文本框</summary>
        
        var $el = $('#'+tid );
        if( $el.length <=0 )
            return;

        var icon = $el.attr('icon');
        var title = $el.attr('title');
        var $html = $el.html();
        var $box = UI.HBox({
            "icon": icon,
            "title": title,
            "size": size
        });
        $box.addClass('box_text').find('.home_box_detail').append($html);
        return $box;
    };

    TianvPageView.prototype.Icon = function(url){
        /// <summary>生成图标页</summary>
        
        var obj;
        if(typeof(url.tag) == 'undefined' ){
            obj = this.LoadData( url    );
        }
        else{
            obj = url;
        }
        if (!obj) return;

        var $tabs = UI.Tab(obj.tag);

        var $content = $tabs.find('.tabs_content');
        $content.addClass('page_icon');
        
        //图标列表
        $.each(obj.iconlists, function (index, temp) {
            var $box = UI.HBox(temp);
            $box.css('margin-top', 10);
            var $icons = UI.BIcon(temp);
            $box.find('.home_box_detail').append($icons);
            $box.appendTo($content);
        });
        
        var $container = elements.frame.main;
        $container.append($tabs);

        $content.data('obj', obj );
        return $content;
    };
    
    TianvPageView.prototype.Text = function(url){
        /// <summary>生成纯文本内容</summary>
        
        var obj;
        if(typeof(url.tag) == 'undefined' ){
            obj = this.LoadData( url    );
        }
        else{
            obj = url;
        }
        if (!obj) return;

        var $tabs = UI.Tab(obj.tag);

        var $content = $tabs.find('.tabs_content');
        $content.addClass('page_text');
        
        var $box1 = getTextBox( 'tmpl_box_full', 7 );
        if($box1) $box1.appendTo($content);

        var $box2 = getTextBox( 'tmpl_box_what', 5 );
        if($box2) $box2.appendTo($content);

        var $box3 = getTextBox( 'tmpl_box_tip', 2 );
        if($box3) $box3.css('position','absolute').appendTo($content);

        var $box4 = getTextBox( 'tmpl_box_why', 5 );
        if($box4) $box4.appendTo($content);

        var $box5 = getTextBox( 'tmpl_box_how', 5 );
        if($box5) $box5.appendTo($content);
        
        var $container = elements.frame.main;
        $container.append($tabs);
        
        $content.data('obj', obj );
        return $content;
    };

    TianvPageView.prototype.IconWithText = function(url){
        /// <summary>生成图标、文本混合</summary>
        
        var obj;
        if(typeof(url.tag) == 'undefined' ){
            obj = this.LoadData( url    );
        }
        else{
            obj = url;
        }
        if (!obj) return;

        var $tabs = UI.Tab(obj.tag);

        var $content = $tabs.find('.tabs_content');
        $content.addClass('page_icontext');

        //图标列表
        $.each(obj.iconlists, function (index, temp) {
            var $box = UI.HBox(temp);
            $box.css('margin-top', 10);
            var $icons = UI.BIcon(temp);
            $box.find('.home_box_detail').append($icons);
            $box.appendTo($content);
        });
        
        var $box1 = getTextBox( 'tmpl_box_full', 8 );
        if($box1) $box1.appendTo($content);

        var $box2 = getTextBox( 'tmpl_box_what', 5 );
        if($box2) $box2.appendTo($content);

        var $box3 = getTextBox( 'tmpl_box_tip', 3 );
        if($box3) $box3.appendTo($content);//.css('position','absolute')

        var $box4 = getTextBox( 'tmpl_box_why', 5 );
        if($box4) $box4.appendTo($content);

        var $box5 = getTextBox( 'tmpl_box_how', 5 );
        if($box5) $box5.appendTo($content);
        
        var $container = elements.frame.main;
        $container.append($tabs);
        
        $content.data('obj', obj );
        return $content;
    };

    TianvPageView.prototype.List = function(url, GridImage )
    {
        var curl = elements.frame.main.data('url');
        var query = '';
        if (curl.indexOf('?') >= 0)
            query = curl.substr(curl.lastIndexOf('?')+1);//.replace('?', '');''.lastIndexOf

        var obj;
        if(typeof(url.tag) == 'undefined' ){
            obj = this.LoadData( url, query    );
        }
        else{
            obj = url;
        }
        if (!obj) return;

        var $tabs = UI.Tab(obj.tag);

        var $content = $tabs.find('.tabs_content');
        $content.addClass('page_list');

        var $guid;
        if( GridImage ){
            $guid = UI.GridImage( obj.gridData );
        }
        else{
            $guid = UI.Grid( obj.gridData );
        }

        $content.append( $guid );
        
        var $container = elements.frame.main;
        $container.append($tabs);
        
        $content.data('obj', obj );
        return $content;
    };

    
})(jQuery);



(function ($) {

    TianvBoxView.prototype.LoadForm = function (guid,viewUrl,codeUrl){
        /// <summary>加载表单</summary>

        var $box = $('#box_' + guid);
        var box = $box.data('ui');

        var query = '';
        var url = box.url;
        if (url.indexOf('?') >= 0) {
            query = '&' + url.substr(url.indexOf('?') + 1);
        }

        box.showLoading();

        //输入框
        var form;
        var formText = $.ajax({
            url: viewUrl + query,
            async: false,
            cache: false
        }).responseText;
        try {
            form = jQuery.parseJSON(formText);
        } catch (e) {
            console.log( formText );
        }

        //预设值
        var info;
        if (query.length >= 1) {
            var infoText = $.ajax({
                url: codeUrl + query,
                async: false,
                cache: false
            }).responseText;
            info = jQuery.parseJSON(infoText);
            //checkLogin(info);

            if (info && info.success == false && info.str == 'user') {
                return;
            }
        }
        if(info) $box.data('info', info);

        var form_items = $.extend(form.form, { guid: guid, action: codeUrl + query });
        var $form = UI.Form.Create( form.form );
        if (info) UI.Form.SetValues($form, info );

        $form.submit(function () {
            box.processForm(codeUrl + query);
            return false;
        });

        box.showHtml( $form );
        
        var $bSubmit = UI.Button.Create('button', lan.Form.Button.Submit, function(){$form.submit();});
        box.showButtons( [$bSubmit] );

        return box;
    };
    
})(jQuery);


/* Tianv.UI.A.js */
(function ($) {

    hrefClickFns.push(function ($a) {
        if (!$a.hasClass('icon_btn'))
            return;

        var url = $a.attr('href');
        $a.hide();
        $.ajax({
            url: url,
            cache: false,
            success: function (data) {
                if (data.success) {
                    $a.find('img').attr('class', 'picon picon_' + data.args);
                    $a.show();

                    if (data.refresh) {
                        Views.Page.ReflashData();
                    }
                    if (data.refreshmenu) {
                        Views.Page.ReflashMenu();
                    }
                }
                else {
                    $a.find('img').attr('class', 'picon picon_error');
                    $a.show();

                    var error_title = Utils.getText('lan.Ajax.Failure');
                    UI.MessageBox.ShowWarning('error', error_title, Utils.getText(data.str));
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                $a.find('img').attr('class', 'picon picon_error');
                $a.show();

                var error_title = Utils.getText('lan.Ajax.Failure');
                var error_text = Utils.getText('lan.Ajax.Error.E' + xhr.status);
                UI.MessageBox.ShowError('error', error_title, error_text);
            }
        });

        return true;
    });

    hrefClickFns.push(function ($a) {
        var target = $a.attr('target');

        if (!target || target != 'dbox') {
            return;
        }

        var boxData = $a.data('dbox');
        if (boxData) {
            boxData['url'] = $a.attr('href');
        }
        else {
            boxData = {
                width: $a.attr('boxwidth'),
                height: $a.attr('boxheight'),
                icon: $a.attr('boxicon'),
                title: $a.attr('boxtitle') ? $a.attr('boxtitle') : $a.children('span').html(),
                url: $a.attr('href')
            };
            if (!boxData.icon && $a.find('img').length >= 1) {
                boxData.icon = $a.find('img').attr('class').substr('picon picon_'.length) //picon picon_shape_square_delete
            }
        }

        var confirmData = $a.data('confirm');
        if (!confirmData && $a.attr('confirm')) {
            confirmData = {
                title: $a.attr('confirm_title'),
                text: $a.attr('confirm_text')
            };
            boxData.title = confirmData.title;
        }

        var $el = UI.Box(boxData); // new TianvBox(boxData);
        var box = $el.data('ui');
        //var $el = box.Show();
        //$el.data('ui', box);
        //$('body').append($el);

        var ids = new Array();
        if ($a.data('postData')) {
            var postData = $a.data('postData');
            if (typeof (postData.items.length) != "undefined" && postData.items.length >= 1) {
                postData.items.find('input:checked[name=id]').each(function () {
                    ids.push($(this).val());
                });
            }
            else {
                $(postData.items).each(function () {
                    ids.push($(this).val());
                });
            }
            if (postData.min && postData.min > ids.length) {
                box.Msg.showWarning(box, lan.Validate.SelectMin.replace('{n}', postData.min), function () { box.Close(); });
                return true;
            }
        }

        if (confirmData) {
            box.Msg.showConfirm(box, confirmData.text, function () { box.processUrl(ids); }, function () { box.Close(); });
        }
        else {
            if (boxData.url) {
                box.Refresh();
            }
        }

        return true;
    });
})(jQuery);

/* Tianv.UI.Input.js */

$(document).delegate(".input_btn", "change", function () {
    //    var $this = $(this);
    //    for (var i = 0; i < hrefClickFns.length; i++) {
    //        var fn = hrefClickFns[i];
    //        var processed = fn($this);
    //        if (processed) {
    //            return false;
    //        }
    //    }
    //    return true;
    //});
    //$('.input_btn').live('change', function () {
    var me = $(this);
    var url = me.attr('url');
    var data = {
        val: me.val()
    };
    me.val('');
    $.ajax({
        url: url,
        cache: false,
        data: data,
        success: function (data) {
            if (data.success) {
                me.val(data.args);
                if (data.refresh) {
                    Views.Page.ReflashData();
                }
            }
            else {
                var error_title = Utils.getText('lan.Ajax.Failure');
                UI.MessageBox.ShowError('exclamation', error_title, data.args);
                me.val('');
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            var error_title = Utils.getText('lan.Ajax.Failure');
            var error_text = Utils.getText('lan.Ajax.Error.E' + xhr.status);
            UI.MessageBox.ShowError('exclamation', error_title, error_text);
            me.val('');
        }
    });
});

